blob: 8c4c182ba5b2e33ad51bfb179a994d14c5371a29 [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
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600132 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
133 glslang::TLayoutPacking, const glslang::TQualifier&);
134 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
135 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700136 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700137 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800138 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600139 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700140 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700141 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
142 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 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 +0100144 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600145
John Kessenich6fccb3c2016-09-19 16:01:41 -0600146 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 void makeFunctions(const glslang::TIntermSequence&);
148 void makeGlobalInitializers(const glslang::TIntermSequence&);
149 void visitFunctions(const glslang::TIntermSequence&);
150 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800151 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600152 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
153 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
155
qining25262b32016-05-06 17:25:16 -0400156 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);
157 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
158 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 +0800159 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 +0800160 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 -0600161 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 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 +0800163 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xub7072052016-09-26 15:53:40 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600165 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 +0800166 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
168 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700169 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400172 spv::Id createSpvConstant(const glslang::TIntermTyped&);
173 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600174 bool isTrivialLeaf(const glslang::TIntermTyped* node);
175 bool isTrivial(const glslang::TIntermTyped* node);
176 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800177 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600178
179 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600180 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700181 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600182 int sequenceDepth;
183
Lei Zhang17535f72016-05-04 15:55:59 -0400184 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400185
John Kessenich140f3df2015-06-26 16:58:36 -0600186 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
187 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700188 bool inEntryPoint;
189 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700190 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 -0700191 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600192 const glslang::TIntermediate* glslangIntermediate;
193 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800194 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600195
John Kessenich2f273362015-07-18 22:34:27 -0600196 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600197 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600198 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700199 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600200 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 -0600201 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600202};
203
204//
205// Helper functions for translating glslang representations to SPIR-V enumerants.
206//
207
208// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700209spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600210{
John Kessenich66e2faf2016-03-12 18:34:36 -0700211 switch (source) {
212 case glslang::EShSourceGlsl:
213 switch (profile) {
214 case ENoProfile:
215 case ECoreProfile:
216 case ECompatibilityProfile:
217 return spv::SourceLanguageGLSL;
218 case EEsProfile:
219 return spv::SourceLanguageESSL;
220 default:
221 return spv::SourceLanguageUnknown;
222 }
223 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400224 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
225 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtSampler)
255 return spv::StorageClassUniformConstant;
256 else if (type.getBasicType() == glslang::EbtAtomicUint)
257 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600265 // 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 -0600266 } else {
267 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700268 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
269 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
271 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::StorageClassFunction;
275 }
276 }
277}
278
279// Translate glslang sampler type to SPIR-V dimensionality.
280spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
281{
282 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700283 case glslang::Esd1D: return spv::Dim1D;
284 case glslang::Esd2D: return spv::Dim2D;
285 case glslang::Esd3D: return spv::Dim3D;
286 case glslang::EsdCube: return spv::DimCube;
287 case glslang::EsdRect: return spv::DimRect;
288 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700289 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::Dim2D;
293 }
294}
295
John Kessenichf6640762016-08-01 19:44:00 -0600296// Translate glslang precision to SPIR-V precision decorations.
297spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
John Kessenichf6640762016-08-01 19:44:00 -0600299 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700300 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600301 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::NoPrecision;
304 }
305}
306
John Kessenichf6640762016-08-01 19:44:00 -0600307// Translate glslang type to SPIR-V precision decorations.
308spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
309{
310 return TranslatePrecisionDecoration(type.getQualifier().precision);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V block decorations.
314spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
315{
316 if (type.getBasicType() == glslang::EbtBlock) {
317 switch (type.getQualifier().storage) {
318 case glslang::EvqUniform: return spv::DecorationBlock;
319 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
320 case glslang::EvqVaryingIn: return spv::DecorationBlock;
321 case glslang::EvqVaryingOut: return spv::DecorationBlock;
322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 break;
325 }
326 }
327
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329}
330
Rex Xu1da878f2016-02-21 20:59:01 +0800331// Translate glslang type to SPIR-V memory decorations.
332void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
333{
334 if (qualifier.coherent)
335 memory.push_back(spv::DecorationCoherent);
336 if (qualifier.volatil)
337 memory.push_back(spv::DecorationVolatile);
338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
David Netoa901ffe2016-06-08 14:11:40 +0100442// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
443// associated capabilities when required. For some built-in variables, a capability
444// is generated only when using the variable in an executable instruction, but not when
445// just declaring a struct member variable with it. This is true for PointSize,
446// ClipDistance, and CullDistance.
447spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600448{
449 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700450 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600451 // Defer adding the capability until the built-in is actually used.
452 if (! memberDeclaration) {
453 switch (glslangIntermediate->getStage()) {
454 case EShLangGeometry:
455 builder.addCapability(spv::CapabilityGeometryPointSize);
456 break;
457 case EShLangTessControl:
458 case EShLangTessEvaluation:
459 builder.addCapability(spv::CapabilityTessellationPointSize);
460 break;
461 default:
462 break;
463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 }
465 return spv::BuiltInPointSize;
466
John Kessenichebb50532016-05-16 19:22:05 -0600467 // These *Distance capabilities logically belong here, but if the member is declared and
468 // then never used, consumers of SPIR-V prefer the capability not be declared.
469 // They are now generated when used, rather than here when declared.
470 // Potentially, the specification should be more clear what the minimum
471 // use needed is to trigger the capability.
472 //
John Kessenich92187592016-02-01 13:45:25 -0700473 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100474 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600475 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInClipDistance;
477
478 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600480 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInCullDistance;
482
483 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500484 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700485 return spv::BuiltInViewportIndex;
486
John Kessenich5e801132016-02-15 11:09:46 -0700487 case glslang::EbvSampleId:
488 builder.addCapability(spv::CapabilitySampleRateShading);
489 return spv::BuiltInSampleId;
490
491 case glslang::EbvSamplePosition:
492 builder.addCapability(spv::CapabilitySampleRateShading);
493 return spv::BuiltInSamplePosition;
494
495 case glslang::EbvSampleMask:
496 builder.addCapability(spv::CapabilitySampleRateShading);
497 return spv::BuiltInSampleMask;
498
John Kessenich78a45572016-07-08 14:05:15 -0600499 case glslang::EbvLayer:
500 builder.addCapability(spv::CapabilityGeometry);
501 return spv::BuiltInLayer;
502
John Kessenich140f3df2015-06-26 16:58:36 -0600503 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600504 case glslang::EbvVertexId: return spv::BuiltInVertexId;
505 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700506 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
507 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseVertex;
513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
John Kessenichda581a22015-10-14 14:10:30 -0600519 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800520 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
521 builder.addCapability(spv::CapabilityDrawParameters);
522 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200523
524 case glslang::EbvPrimitiveId:
525 if (glslangIntermediate->getStage() == EShLangFragment)
526 builder.addCapability(spv::CapabilityGeometry);
527 return spv::BuiltInPrimitiveId;
528
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
531 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
532 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
533 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
534 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
535 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
536 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
538 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
539 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
540 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
541 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
542 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
543 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
544 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800545
Rex Xu574ab042016-04-14 16:53:07 +0800546 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800547 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800548 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
549 return spv::BuiltInSubgroupSize;
550
Rex Xu574ab042016-04-14 16:53:07 +0800551 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800552 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
554 return spv::BuiltInSubgroupLocalInvocationId;
555
Rex Xu574ab042016-04-14 16:53:07 +0800556 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800557 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
558 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
559 return spv::BuiltInSubgroupEqMaskKHR;
560
Rex Xu574ab042016-04-14 16:53:07 +0800561 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800562 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
563 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
564 return spv::BuiltInSubgroupGeMaskKHR;
565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupGtMaskKHR;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLeMaskKHR;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupLtMaskKHR;
580
Rex Xu9d93a232016-05-05 12:30:44 +0800581#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800582 case glslang::EbvBaryCoordNoPersp:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspAMD;
585
586 case glslang::EbvBaryCoordNoPerspCentroid:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
589
590 case glslang::EbvBaryCoordNoPerspSample:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordNoPerspSampleAMD;
593
594 case glslang::EbvBaryCoordSmooth:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothAMD;
597
598 case glslang::EbvBaryCoordSmoothCentroid:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothCentroidAMD;
601
602 case glslang::EbvBaryCoordSmoothSample:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordSmoothSampleAMD;
605
606 case glslang::EbvBaryCoordPullModel:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800609#endif
John Kessenich4016e382016-07-15 11:53:56 -0600610 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600611 }
612}
613
Rex Xufc618912015-09-09 16:42:49 +0800614// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700615spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800616{
617 assert(type.getBasicType() == glslang::EbtSampler);
618
John Kessenich5d0fa972016-02-15 11:57:00 -0700619 // Check for capabilities
620 switch (type.getQualifier().layoutFormat) {
621 case glslang::ElfRg32f:
622 case glslang::ElfRg16f:
623 case glslang::ElfR11fG11fB10f:
624 case glslang::ElfR16f:
625 case glslang::ElfRgba16:
626 case glslang::ElfRgb10A2:
627 case glslang::ElfRg16:
628 case glslang::ElfRg8:
629 case glslang::ElfR16:
630 case glslang::ElfR8:
631 case glslang::ElfRgba16Snorm:
632 case glslang::ElfRg16Snorm:
633 case glslang::ElfRg8Snorm:
634 case glslang::ElfR16Snorm:
635 case glslang::ElfR8Snorm:
636
637 case glslang::ElfRg32i:
638 case glslang::ElfRg16i:
639 case glslang::ElfRg8i:
640 case glslang::ElfR16i:
641 case glslang::ElfR8i:
642
643 case glslang::ElfRgb10a2ui:
644 case glslang::ElfRg32ui:
645 case glslang::ElfRg16ui:
646 case glslang::ElfRg8ui:
647 case glslang::ElfR16ui:
648 case glslang::ElfR8ui:
649 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
650 break;
651
652 default:
653 break;
654 }
655
656 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800657 switch (type.getQualifier().layoutFormat) {
658 case glslang::ElfNone: return spv::ImageFormatUnknown;
659 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
660 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
661 case glslang::ElfR32f: return spv::ImageFormatR32f;
662 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
663 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
664 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
665 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
666 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
667 case glslang::ElfR16f: return spv::ImageFormatR16f;
668 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
669 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
670 case glslang::ElfRg16: return spv::ImageFormatRg16;
671 case glslang::ElfRg8: return spv::ImageFormatRg8;
672 case glslang::ElfR16: return spv::ImageFormatR16;
673 case glslang::ElfR8: return spv::ImageFormatR8;
674 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
675 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
676 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
677 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
678 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
679 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
680 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
681 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
682 case glslang::ElfR32i: return spv::ImageFormatR32i;
683 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
684 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
685 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
686 case glslang::ElfR16i: return spv::ImageFormatR16i;
687 case glslang::ElfR8i: return spv::ImageFormatR8i;
688 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
689 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
690 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
691 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
692 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
693 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
694 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
695 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
696 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
697 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600698 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800699 }
700}
701
qining25262b32016-05-06 17:25:16 -0400702// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700703// descriptor set.
704bool IsDescriptorResource(const glslang::TType& type)
705{
John Kessenichf7497e22016-03-08 21:36:22 -0700706 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700707 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700708 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700709
710 // non block...
711 // basically samplerXXX/subpass/sampler/texture are all included
712 // if they are the global-scope-class, not the function parameter
713 // (or local, if they ever exist) class.
714 if (type.getBasicType() == glslang::EbtSampler)
715 return type.getQualifier().isUniformOrBuffer();
716
717 // None of the above.
718 return false;
719}
720
John Kesseniche0b6cad2015-12-24 10:30:13 -0700721void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
722{
723 if (child.layoutMatrix == glslang::ElmNone)
724 child.layoutMatrix = parent.layoutMatrix;
725
726 if (parent.invariant)
727 child.invariant = true;
728 if (parent.nopersp)
729 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800730#ifdef AMD_EXTENSIONS
731 if (parent.explicitInterp)
732 child.explicitInterp = true;
733#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700734 if (parent.flat)
735 child.flat = true;
736 if (parent.centroid)
737 child.centroid = true;
738 if (parent.patch)
739 child.patch = true;
740 if (parent.sample)
741 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800742 if (parent.coherent)
743 child.coherent = true;
744 if (parent.volatil)
745 child.volatil = true;
746 if (parent.restrict)
747 child.restrict = true;
748 if (parent.readonly)
749 child.readonly = true;
750 if (parent.writeonly)
751 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700752}
753
John Kessenichf2b7f332016-09-01 17:05:23 -0600754bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700755{
John Kessenich7b9fa252016-01-21 18:56:57 -0700756 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600757 // - struct members might inherit from a struct declaration
758 // (note that non-block structs don't explicitly inherit,
759 // only implicitly, meaning no decoration involved)
760 // - affect decorations on the struct members
761 // (note smooth does not, and expecting something like volatile
762 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700763 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600764 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700765}
766
John Kessenich140f3df2015-06-26 16:58:36 -0600767//
768// Implement the TGlslangToSpvTraverser class.
769//
770
Lei Zhang17535f72016-05-04 15:55:59 -0400771TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600772 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
773 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400774 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700775 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600776 glslangIntermediate(glslangIntermediate)
777{
778 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
779
780 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700781 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600782 stdBuiltins = builder.import("GLSL.std.450");
783 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600784 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
785 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600786
787 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600788 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
789 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600790 builder.addSourceExtension(it->c_str());
791
792 // Add the top-level modes for this shader.
793
John Kessenich92187592016-02-01 13:45:25 -0700794 if (glslangIntermediate->getXfbMode()) {
795 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600796 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700797 }
John Kessenich140f3df2015-06-26 16:58:36 -0600798
799 unsigned int mode;
800 switch (glslangIntermediate->getStage()) {
801 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600802 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600803 break;
804
805 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600806 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600807 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
808 break;
809
810 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600811 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600812 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700813 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
814 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
815 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600816 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600817 }
John Kessenich4016e382016-07-15 11:53:56 -0600818 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600819 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
820
John Kesseniche6903322015-10-13 16:29:02 -0600821 switch (glslangIntermediate->getVertexSpacing()) {
822 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
823 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
824 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600825 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600826 }
John Kessenich4016e382016-07-15 11:53:56 -0600827 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600828 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
829
830 switch (glslangIntermediate->getVertexOrder()) {
831 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
832 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600833 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600834 }
John Kessenich4016e382016-07-15 11:53:56 -0600835 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600836 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
837
838 if (glslangIntermediate->getPointMode())
839 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600840 break;
841
842 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600843 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600844 switch (glslangIntermediate->getInputPrimitive()) {
845 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
846 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
847 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700848 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600849 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600850 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600851 }
John Kessenich4016e382016-07-15 11:53:56 -0600852 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600853 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600854
John Kessenich140f3df2015-06-26 16:58:36 -0600855 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
856
857 switch (glslangIntermediate->getOutputPrimitive()) {
858 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
859 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
860 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600861 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600862 }
John Kessenich4016e382016-07-15 11:53:56 -0600863 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600864 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
865 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
866 break;
867
868 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600869 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600870 if (glslangIntermediate->getPixelCenterInteger())
871 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600872
John Kessenich140f3df2015-06-26 16:58:36 -0600873 if (glslangIntermediate->getOriginUpperLeft())
874 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600875 else
876 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600877
878 if (glslangIntermediate->getEarlyFragmentTests())
879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
880
881 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600882 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
883 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600884 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600885 }
John Kessenich4016e382016-07-15 11:53:56 -0600886 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600887 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
888
889 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
890 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600891 break;
892
893 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600894 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600895 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
896 glslangIntermediate->getLocalSize(1),
897 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600898 break;
899
900 default:
901 break;
902 }
John Kessenich140f3df2015-06-26 16:58:36 -0600903}
904
John Kessenichfca82622016-11-26 13:23:20 -0700905// Finish creating SPV, after the traversal is complete.
906void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700907{
John Kessenich517fe7a2016-11-26 13:31:47 -0700908 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700909 builder.setBuildPoint(shaderEntry->getLastBlock());
910 builder.leaveFunction();
911 }
912
John Kessenich7ba63412015-12-20 17:37:07 -0700913 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100914 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
915 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700916
qiningda397332016-03-09 19:54:03 -0500917 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700918}
919
John Kessenichfca82622016-11-26 13:23:20 -0700920// Write the SPV into 'out'.
921void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600922{
John Kessenichfca82622016-11-26 13:23:20 -0700923 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600924}
925
926//
927// Implement the traversal functions.
928//
929// Return true from interior nodes to have the external traversal
930// continue on to children. Return false if children were
931// already processed.
932//
933
934//
qining25262b32016-05-06 17:25:16 -0400935// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600936// - uniform/input reads
937// - output writes
938// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
939// - something simple that degenerates into the last bullet
940//
941void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
942{
qining75d1d802016-04-06 14:42:01 -0400943 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
944 if (symbol->getType().getQualifier().isSpecConstant())
945 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
946
John Kessenich140f3df2015-06-26 16:58:36 -0600947 // getSymbolId() will set up all the IO decorations on the first call.
948 // Formal function parameters were mapped during makeFunctions().
949 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700950
951 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
952 if (builder.isPointer(id)) {
953 spv::StorageClass sc = builder.getStorageClass(id);
954 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
955 iOSet.insert(id);
956 }
957
958 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700959 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600960 // Prepare to generate code for the access
961
962 // L-value chains will be computed left to right. We're on the symbol now,
963 // which is the left-most part of the access chain, so now is "clear" time,
964 // followed by setting the base.
965 builder.clearAccessChain();
966
967 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700968 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600969 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700970 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600971 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700972 // These are also pure R-values.
973 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600974 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600975 builder.setAccessChainRValue(id);
976 else
977 builder.setAccessChainLValue(id);
978 }
979}
980
981bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
982{
qining40887662016-04-03 22:20:42 -0400983 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
984 if (node->getType().getQualifier().isSpecConstant())
985 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
986
John Kessenich140f3df2015-06-26 16:58:36 -0600987 // First, handle special cases
988 switch (node->getOp()) {
989 case glslang::EOpAssign:
990 case glslang::EOpAddAssign:
991 case glslang::EOpSubAssign:
992 case glslang::EOpMulAssign:
993 case glslang::EOpVectorTimesMatrixAssign:
994 case glslang::EOpVectorTimesScalarAssign:
995 case glslang::EOpMatrixTimesScalarAssign:
996 case glslang::EOpMatrixTimesMatrixAssign:
997 case glslang::EOpDivAssign:
998 case glslang::EOpModAssign:
999 case glslang::EOpAndAssign:
1000 case glslang::EOpInclusiveOrAssign:
1001 case glslang::EOpExclusiveOrAssign:
1002 case glslang::EOpLeftShiftAssign:
1003 case glslang::EOpRightShiftAssign:
1004 // A bin-op assign "a += b" means the same thing as "a = a + b"
1005 // where a is evaluated before b. For a simple assignment, GLSL
1006 // says to evaluate the left before the right. So, always, left
1007 // node then right node.
1008 {
1009 // get the left l-value, save it away
1010 builder.clearAccessChain();
1011 node->getLeft()->traverse(this);
1012 spv::Builder::AccessChain lValue = builder.getAccessChain();
1013
1014 // evaluate the right
1015 builder.clearAccessChain();
1016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001017 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001018
1019 if (node->getOp() != glslang::EOpAssign) {
1020 // the left is also an r-value
1021 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001022 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001023
1024 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001025 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001026 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001027 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1028 node->getType().getBasicType());
1029
1030 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001031 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001032 }
1033
1034 // store the result
1035 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001036 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001037
1038 // assignments are expressions having an rValue after they are evaluated...
1039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(rValue);
1041 }
1042 return false;
1043 case glslang::EOpIndexDirect:
1044 case glslang::EOpIndexDirectStruct:
1045 {
1046 // Get the left part of the access chain.
1047 node->getLeft()->traverse(this);
1048
1049 // Add the next element in the chain
1050
David Netoa901ffe2016-06-08 14:11:40 +01001051 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001052 if (! node->getLeft()->getType().isArray() &&
1053 node->getLeft()->getType().isVector() &&
1054 node->getOp() == glslang::EOpIndexDirect) {
1055 // This is essentially a hard-coded vector swizzle of size 1,
1056 // so short circuit the access-chain stuff with a swizzle.
1057 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001058 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001059 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001060 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001061 int spvIndex = glslangIndex;
1062 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1063 node->getOp() == glslang::EOpIndexDirectStruct)
1064 {
1065 // This may be, e.g., an anonymous block-member selection, which generally need
1066 // index remapping due to hidden members in anonymous blocks.
1067 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1068 assert(remapper.size() > 0);
1069 spvIndex = remapper[glslangIndex];
1070 }
John Kessenichebb50532016-05-16 19:22:05 -06001071
David Netoa901ffe2016-06-08 14:11:40 +01001072 // normal case for indexing array or structure or block
1073 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1074
1075 // Add capabilities here for accessing PointSize and clip/cull distance.
1076 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001077 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001078 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001079 }
1080 }
1081 return false;
1082 case glslang::EOpIndexIndirect:
1083 {
1084 // Structure or array or vector indirection.
1085 // Will use native SPIR-V access-chain for struct and array indirection;
1086 // matrices are arrays of vectors, so will also work for a matrix.
1087 // Will use the access chain's 'component' for variable index into a vector.
1088
1089 // This adapter is building access chains left to right.
1090 // Set up the access chain to the left.
1091 node->getLeft()->traverse(this);
1092
1093 // save it so that computing the right side doesn't trash it
1094 spv::Builder::AccessChain partial = builder.getAccessChain();
1095
1096 // compute the next index in the chain
1097 builder.clearAccessChain();
1098 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001099 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
1101 // restore the saved access chain
1102 builder.setAccessChain(partial);
1103
1104 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001105 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001106 else
John Kessenichfa668da2015-09-13 14:46:30 -06001107 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001108 }
1109 return false;
1110 case glslang::EOpVectorSwizzle:
1111 {
1112 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001113 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001114 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001115 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001116 }
1117 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001118 case glslang::EOpLogicalOr:
1119 case glslang::EOpLogicalAnd:
1120 {
1121
1122 // These may require short circuiting, but can sometimes be done as straight
1123 // binary operations. The right operand must be short circuited if it has
1124 // side effects, and should probably be if it is complex.
1125 if (isTrivial(node->getRight()->getAsTyped()))
1126 break; // handle below as a normal binary operation
1127 // otherwise, we need to do dynamic short circuiting on the right operand
1128 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1129 builder.clearAccessChain();
1130 builder.setAccessChainRValue(result);
1131 }
1132 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001133 default:
1134 break;
1135 }
1136
1137 // Assume generic binary op...
1138
John Kessenich32cfd492016-02-02 12:37:46 -07001139 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001140 builder.clearAccessChain();
1141 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001142 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001143
John Kessenich32cfd492016-02-02 12:37:46 -07001144 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001145 builder.clearAccessChain();
1146 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001147 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001148
John Kessenich32cfd492016-02-02 12:37:46 -07001149 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001150 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001151 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001152 convertGlslangToSpvType(node->getType()), left, right,
1153 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001154
John Kessenich50e57562015-12-21 21:21:11 -07001155 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001156 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001157 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001158 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001159 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001160 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001161 return false;
1162 }
John Kessenich140f3df2015-06-26 16:58:36 -06001163}
1164
1165bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1166{
qining40887662016-04-03 22:20:42 -04001167 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1168 if (node->getType().getQualifier().isSpecConstant())
1169 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1170
John Kessenichfc51d282015-08-19 13:34:18 -06001171 spv::Id result = spv::NoResult;
1172
1173 // try texturing first
1174 result = createImageTextureFunctionCall(node);
1175 if (result != spv::NoResult) {
1176 builder.clearAccessChain();
1177 builder.setAccessChainRValue(result);
1178
1179 return false; // done with this node
1180 }
1181
1182 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001183
1184 if (node->getOp() == glslang::EOpArrayLength) {
1185 // Quite special; won't want to evaluate the operand.
1186
1187 // Normal .length() would have been constant folded by the front-end.
1188 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001189 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001190 assert(node->getOperand()->getType().isRuntimeSizedArray());
1191 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1192 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001193 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1194 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001195
1196 builder.clearAccessChain();
1197 builder.setAccessChainRValue(length);
1198
1199 return false;
1200 }
1201
John Kessenichfc51d282015-08-19 13:34:18 -06001202 // Start by evaluating the operand
1203
John Kessenich8c8505c2016-07-26 12:50:38 -06001204 // Does it need a swizzle inversion? If so, evaluation is inverted;
1205 // operate first on the swizzle base, then apply the swizzle.
1206 spv::Id invertedType = spv::NoType;
1207 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1208 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1209 invertedType = getInvertedSwizzleType(*node->getOperand());
1210
John Kessenich140f3df2015-06-26 16:58:36 -06001211 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001212 if (invertedType != spv::NoType)
1213 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1214 else
1215 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001216
Rex Xufc618912015-09-09 16:42:49 +08001217 spv::Id operand = spv::NoResult;
1218
1219 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1220 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001221 node->getOp() == glslang::EOpAtomicCounter ||
1222 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001223 operand = builder.accessChainGetLValue(); // Special case l-value operands
1224 else
John Kessenich32cfd492016-02-02 12:37:46 -07001225 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001226
John Kessenichf6640762016-08-01 19:44:00 -06001227 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001228 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001229
1230 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001231 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001232 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001233
1234 // if not, then possibly an operation
1235 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001236 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001237
1238 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001239 if (invertedType)
1240 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1241
John Kessenich140f3df2015-06-26 16:58:36 -06001242 builder.clearAccessChain();
1243 builder.setAccessChainRValue(result);
1244
1245 return false; // done with this node
1246 }
1247
1248 // it must be a special case, check...
1249 switch (node->getOp()) {
1250 case glslang::EOpPostIncrement:
1251 case glslang::EOpPostDecrement:
1252 case glslang::EOpPreIncrement:
1253 case glslang::EOpPreDecrement:
1254 {
1255 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001256 spv::Id one = 0;
1257 if (node->getBasicType() == glslang::EbtFloat)
1258 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001259 else if (node->getBasicType() == glslang::EbtDouble)
1260 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001261#ifdef AMD_EXTENSIONS
1262 else if (node->getBasicType() == glslang::EbtFloat16)
1263 one = builder.makeFloat16Constant(1.0F);
1264#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001265 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1266 one = builder.makeInt64Constant(1);
1267 else
1268 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001269 glslang::TOperator op;
1270 if (node->getOp() == glslang::EOpPreIncrement ||
1271 node->getOp() == glslang::EOpPostIncrement)
1272 op = glslang::EOpAdd;
1273 else
1274 op = glslang::EOpSub;
1275
John Kessenichf6640762016-08-01 19:44:00 -06001276 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001277 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001278 convertGlslangToSpvType(node->getType()), operand, one,
1279 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001280 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001281
1282 // The result of operation is always stored, but conditionally the
1283 // consumed result. The consumed result is always an r-value.
1284 builder.accessChainStore(result);
1285 builder.clearAccessChain();
1286 if (node->getOp() == glslang::EOpPreIncrement ||
1287 node->getOp() == glslang::EOpPreDecrement)
1288 builder.setAccessChainRValue(result);
1289 else
1290 builder.setAccessChainRValue(operand);
1291 }
1292
1293 return false;
1294
1295 case glslang::EOpEmitStreamVertex:
1296 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1297 return false;
1298 case glslang::EOpEndStreamPrimitive:
1299 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1300 return false;
1301
1302 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001303 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001304 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001305 }
John Kessenich140f3df2015-06-26 16:58:36 -06001306}
1307
1308bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1309{
qining27e04a02016-04-14 16:40:20 -04001310 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1311 if (node->getType().getQualifier().isSpecConstant())
1312 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1313
John Kessenichfc51d282015-08-19 13:34:18 -06001314 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001315 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1316 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001317
1318 // try texturing
1319 result = createImageTextureFunctionCall(node);
1320 if (result != spv::NoResult) {
1321 builder.clearAccessChain();
1322 builder.setAccessChainRValue(result);
1323
1324 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001325 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001326 // "imageStore" is a special case, which has no result
1327 return false;
1328 }
John Kessenichfc51d282015-08-19 13:34:18 -06001329
John Kessenich140f3df2015-06-26 16:58:36 -06001330 glslang::TOperator binOp = glslang::EOpNull;
1331 bool reduceComparison = true;
1332 bool isMatrix = false;
1333 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001334 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001335
1336 assert(node->getOp());
1337
John Kessenichf6640762016-08-01 19:44:00 -06001338 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001339
1340 switch (node->getOp()) {
1341 case glslang::EOpSequence:
1342 {
1343 if (preVisit)
1344 ++sequenceDepth;
1345 else
1346 --sequenceDepth;
1347
1348 if (sequenceDepth == 1) {
1349 // If this is the parent node of all the functions, we want to see them
1350 // early, so all call points have actual SPIR-V functions to reference.
1351 // In all cases, still let the traverser visit the children for us.
1352 makeFunctions(node->getAsAggregate()->getSequence());
1353
John Kessenich6fccb3c2016-09-19 16:01:41 -06001354 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001355 // anything else gets there, so visit out of order, doing them all now.
1356 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1357
John Kessenich6a60c2f2016-12-08 21:01:59 -07001358 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001359 // so do them manually.
1360 visitFunctions(node->getAsAggregate()->getSequence());
1361
1362 return false;
1363 }
1364
1365 return true;
1366 }
1367 case glslang::EOpLinkerObjects:
1368 {
1369 if (visit == glslang::EvPreVisit)
1370 linkageOnly = true;
1371 else
1372 linkageOnly = false;
1373
1374 return true;
1375 }
1376 case glslang::EOpComma:
1377 {
1378 // processing from left to right naturally leaves the right-most
1379 // lying around in the access chain
1380 glslang::TIntermSequence& glslangOperands = node->getSequence();
1381 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1382 glslangOperands[i]->traverse(this);
1383
1384 return false;
1385 }
1386 case glslang::EOpFunction:
1387 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001388 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001389 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001390 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001391 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001392 } else {
1393 handleFunctionEntry(node);
1394 }
1395 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001396 if (inEntryPoint)
1397 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001398 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001399 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001400 }
1401
1402 return true;
1403 case glslang::EOpParameters:
1404 // Parameters will have been consumed by EOpFunction processing, but not
1405 // the body, so we still visited the function node's children, making this
1406 // child redundant.
1407 return false;
1408 case glslang::EOpFunctionCall:
1409 {
1410 if (node->isUserDefined())
1411 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001412 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1413 if (result) {
1414 builder.clearAccessChain();
1415 builder.setAccessChainRValue(result);
1416 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001417 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001418
1419 return false;
1420 }
1421 case glslang::EOpConstructMat2x2:
1422 case glslang::EOpConstructMat2x3:
1423 case glslang::EOpConstructMat2x4:
1424 case glslang::EOpConstructMat3x2:
1425 case glslang::EOpConstructMat3x3:
1426 case glslang::EOpConstructMat3x4:
1427 case glslang::EOpConstructMat4x2:
1428 case glslang::EOpConstructMat4x3:
1429 case glslang::EOpConstructMat4x4:
1430 case glslang::EOpConstructDMat2x2:
1431 case glslang::EOpConstructDMat2x3:
1432 case glslang::EOpConstructDMat2x4:
1433 case glslang::EOpConstructDMat3x2:
1434 case glslang::EOpConstructDMat3x3:
1435 case glslang::EOpConstructDMat3x4:
1436 case glslang::EOpConstructDMat4x2:
1437 case glslang::EOpConstructDMat4x3:
1438 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001439#ifdef AMD_EXTENSIONS
1440 case glslang::EOpConstructF16Mat2x2:
1441 case glslang::EOpConstructF16Mat2x3:
1442 case glslang::EOpConstructF16Mat2x4:
1443 case glslang::EOpConstructF16Mat3x2:
1444 case glslang::EOpConstructF16Mat3x3:
1445 case glslang::EOpConstructF16Mat3x4:
1446 case glslang::EOpConstructF16Mat4x2:
1447 case glslang::EOpConstructF16Mat4x3:
1448 case glslang::EOpConstructF16Mat4x4:
1449#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001450 isMatrix = true;
1451 // fall through
1452 case glslang::EOpConstructFloat:
1453 case glslang::EOpConstructVec2:
1454 case glslang::EOpConstructVec3:
1455 case glslang::EOpConstructVec4:
1456 case glslang::EOpConstructDouble:
1457 case glslang::EOpConstructDVec2:
1458 case glslang::EOpConstructDVec3:
1459 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001460#ifdef AMD_EXTENSIONS
1461 case glslang::EOpConstructFloat16:
1462 case glslang::EOpConstructF16Vec2:
1463 case glslang::EOpConstructF16Vec3:
1464 case glslang::EOpConstructF16Vec4:
1465#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001466 case glslang::EOpConstructBool:
1467 case glslang::EOpConstructBVec2:
1468 case glslang::EOpConstructBVec3:
1469 case glslang::EOpConstructBVec4:
1470 case glslang::EOpConstructInt:
1471 case glslang::EOpConstructIVec2:
1472 case glslang::EOpConstructIVec3:
1473 case glslang::EOpConstructIVec4:
1474 case glslang::EOpConstructUint:
1475 case glslang::EOpConstructUVec2:
1476 case glslang::EOpConstructUVec3:
1477 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001478 case glslang::EOpConstructInt64:
1479 case glslang::EOpConstructI64Vec2:
1480 case glslang::EOpConstructI64Vec3:
1481 case glslang::EOpConstructI64Vec4:
1482 case glslang::EOpConstructUint64:
1483 case glslang::EOpConstructU64Vec2:
1484 case glslang::EOpConstructU64Vec3:
1485 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001486 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001487 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001488 {
1489 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001490 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001491 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001492 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001493 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001494 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001495 std::vector<spv::Id> constituents;
1496 for (int c = 0; c < (int)arguments.size(); ++c)
1497 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001498 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001499 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001500 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001501 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001502 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 builder.clearAccessChain();
1505 builder.setAccessChainRValue(constructed);
1506
1507 return false;
1508 }
1509
1510 // These six are component-wise compares with component-wise results.
1511 // Forward on to createBinaryOperation(), requesting a vector result.
1512 case glslang::EOpLessThan:
1513 case glslang::EOpGreaterThan:
1514 case glslang::EOpLessThanEqual:
1515 case glslang::EOpGreaterThanEqual:
1516 case glslang::EOpVectorEqual:
1517 case glslang::EOpVectorNotEqual:
1518 {
1519 // Map the operation to a binary
1520 binOp = node->getOp();
1521 reduceComparison = false;
1522 switch (node->getOp()) {
1523 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1524 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1525 default: binOp = node->getOp(); break;
1526 }
1527
1528 break;
1529 }
1530 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001531 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001532 binOp = glslang::EOpMul;
1533 break;
1534 case glslang::EOpOuterProduct:
1535 // two vectors multiplied to make a matrix
1536 binOp = glslang::EOpOuterProduct;
1537 break;
1538 case glslang::EOpDot:
1539 {
qining25262b32016-05-06 17:25:16 -04001540 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001541 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001542 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001543 binOp = glslang::EOpMul;
1544 break;
1545 }
1546 case glslang::EOpMod:
1547 // when an aggregate, this is the floating-point mod built-in function,
1548 // which can be emitted by the one in createBinaryOperation()
1549 binOp = glslang::EOpMod;
1550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001551 case glslang::EOpEmitVertex:
1552 case glslang::EOpEndPrimitive:
1553 case glslang::EOpBarrier:
1554 case glslang::EOpMemoryBarrier:
1555 case glslang::EOpMemoryBarrierAtomicCounter:
1556 case glslang::EOpMemoryBarrierBuffer:
1557 case glslang::EOpMemoryBarrierImage:
1558 case glslang::EOpMemoryBarrierShared:
1559 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001560 case glslang::EOpAllMemoryBarrierWithGroupSync:
1561 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1562 case glslang::EOpWorkgroupMemoryBarrier:
1563 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001564 noReturnValue = true;
1565 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1566 break;
1567
John Kessenich426394d2015-07-23 10:22:48 -06001568 case glslang::EOpAtomicAdd:
1569 case glslang::EOpAtomicMin:
1570 case glslang::EOpAtomicMax:
1571 case glslang::EOpAtomicAnd:
1572 case glslang::EOpAtomicOr:
1573 case glslang::EOpAtomicXor:
1574 case glslang::EOpAtomicExchange:
1575 case glslang::EOpAtomicCompSwap:
1576 atomic = true;
1577 break;
1578
John Kessenich140f3df2015-06-26 16:58:36 -06001579 default:
1580 break;
1581 }
1582
1583 //
1584 // See if it maps to a regular operation.
1585 //
John Kessenich140f3df2015-06-26 16:58:36 -06001586 if (binOp != glslang::EOpNull) {
1587 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1588 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1589 assert(left && right);
1590
1591 builder.clearAccessChain();
1592 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001593 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001594
1595 builder.clearAccessChain();
1596 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001597 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001598
qining25262b32016-05-06 17:25:16 -04001599 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001600 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001601 left->getType().getBasicType(), reduceComparison);
1602
1603 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001604 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001605 builder.clearAccessChain();
1606 builder.setAccessChainRValue(result);
1607
1608 return false;
1609 }
1610
John Kessenich426394d2015-07-23 10:22:48 -06001611 //
1612 // Create the list of operands.
1613 //
John Kessenich140f3df2015-06-26 16:58:36 -06001614 glslang::TIntermSequence& glslangOperands = node->getSequence();
1615 std::vector<spv::Id> operands;
1616 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001617 // special case l-value operands; there are just a few
1618 bool lvalue = false;
1619 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001620 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001621 case glslang::EOpModf:
1622 if (arg == 1)
1623 lvalue = true;
1624 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001625 case glslang::EOpInterpolateAtSample:
1626 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001627#ifdef AMD_EXTENSIONS
1628 case glslang::EOpInterpolateAtVertex:
1629#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001630 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001631 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001632
1633 // Does it need a swizzle inversion? If so, evaluation is inverted;
1634 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001635 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001636 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1637 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1638 }
Rex Xu7a26c172015-12-08 17:12:09 +08001639 break;
Rex Xud4782c12015-09-06 16:30:11 +08001640 case glslang::EOpAtomicAdd:
1641 case glslang::EOpAtomicMin:
1642 case glslang::EOpAtomicMax:
1643 case glslang::EOpAtomicAnd:
1644 case glslang::EOpAtomicOr:
1645 case glslang::EOpAtomicXor:
1646 case glslang::EOpAtomicExchange:
1647 case glslang::EOpAtomicCompSwap:
1648 if (arg == 0)
1649 lvalue = true;
1650 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001651 case glslang::EOpAddCarry:
1652 case glslang::EOpSubBorrow:
1653 if (arg == 2)
1654 lvalue = true;
1655 break;
1656 case glslang::EOpUMulExtended:
1657 case glslang::EOpIMulExtended:
1658 if (arg >= 2)
1659 lvalue = true;
1660 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001661 default:
1662 break;
1663 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001664 builder.clearAccessChain();
1665 if (invertedType != spv::NoType && arg == 0)
1666 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1667 else
1668 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001669 if (lvalue)
1670 operands.push_back(builder.accessChainGetLValue());
1671 else
John Kessenich32cfd492016-02-02 12:37:46 -07001672 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001673 }
John Kessenich426394d2015-07-23 10:22:48 -06001674
1675 if (atomic) {
1676 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001677 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001678 } else {
1679 // Pass through to generic operations.
1680 switch (glslangOperands.size()) {
1681 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001682 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001683 break;
1684 case 1:
qining25262b32016-05-06 17:25:16 -04001685 result = createUnaryOperation(
1686 node->getOp(), precision,
1687 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001688 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001689 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001690 break;
1691 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001692 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001693 break;
1694 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001695 if (invertedType)
1696 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 }
1698
1699 if (noReturnValue)
1700 return false;
1701
1702 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001703 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001704 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001705 } else {
1706 builder.clearAccessChain();
1707 builder.setAccessChainRValue(result);
1708 return false;
1709 }
1710}
1711
1712bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1713{
1714 // This path handles both if-then-else and ?:
1715 // The if-then-else has a node type of void, while
1716 // ?: has a non-void node type
1717 spv::Id result = 0;
1718 if (node->getBasicType() != glslang::EbtVoid) {
1719 // don't handle this as just on-the-fly temporaries, because there will be two names
1720 // and better to leave SSA to later passes
1721 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1722 }
1723
1724 // emit the condition before doing anything with selection
1725 node->getCondition()->traverse(this);
1726
1727 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001728 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001729
1730 if (node->getTrueBlock()) {
1731 // emit the "then" statement
1732 node->getTrueBlock()->traverse(this);
1733 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001734 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001735 }
1736
1737 if (node->getFalseBlock()) {
1738 ifBuilder.makeBeginElse();
1739 // emit the "else" statement
1740 node->getFalseBlock()->traverse(this);
1741 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001742 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001743 }
1744
1745 ifBuilder.makeEndIf();
1746
1747 if (result) {
1748 // GLSL only has r-values as the result of a :?, but
1749 // if we have an l-value, that can be more efficient if it will
1750 // become the base of a complex r-value expression, because the
1751 // next layer copies r-values into memory to use the access-chain mechanism
1752 builder.clearAccessChain();
1753 builder.setAccessChainLValue(result);
1754 }
1755
1756 return false;
1757}
1758
1759bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1760{
1761 // emit and get the condition before doing anything with switch
1762 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001763 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001764
1765 // browse the children to sort out code segments
1766 int defaultSegment = -1;
1767 std::vector<TIntermNode*> codeSegments;
1768 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1769 std::vector<int> caseValues;
1770 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1771 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1772 TIntermNode* child = *c;
1773 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001774 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001775 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001776 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001777 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1778 } else
1779 codeSegments.push_back(child);
1780 }
1781
qining25262b32016-05-06 17:25:16 -04001782 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001783 // statements between the last case and the end of the switch statement
1784 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1785 (int)codeSegments.size() == defaultSegment)
1786 codeSegments.push_back(nullptr);
1787
1788 // make the switch statement
1789 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001790 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001791
1792 // emit all the code in the segments
1793 breakForLoop.push(false);
1794 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1795 builder.nextSwitchSegment(segmentBlocks, s);
1796 if (codeSegments[s])
1797 codeSegments[s]->traverse(this);
1798 else
1799 builder.addSwitchBreak();
1800 }
1801 breakForLoop.pop();
1802
1803 builder.endSwitch(segmentBlocks);
1804
1805 return false;
1806}
1807
1808void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1809{
1810 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001811 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001812
1813 builder.clearAccessChain();
1814 builder.setAccessChainRValue(constant);
1815}
1816
1817bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1818{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001819 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001820 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001821 // Spec requires back edges to target header blocks, and every header block
1822 // must dominate its merge block. Make a header block first to ensure these
1823 // conditions are met. By definition, it will contain OpLoopMerge, followed
1824 // by a block-ending branch. But we don't want to put any other body/test
1825 // instructions in it, since the body/test may have arbitrary instructions,
1826 // including merges of its own.
1827 builder.setBuildPoint(&blocks.head);
1828 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001829 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001830 spv::Block& test = builder.makeNewBlock();
1831 builder.createBranch(&test);
1832
1833 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001834 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001835 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001836 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001837 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1838
1839 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001840 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001841 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001842 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001843 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001844 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001845
1846 builder.setBuildPoint(&blocks.continue_target);
1847 if (node->getTerminal())
1848 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001849 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001850 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001851 builder.createBranch(&blocks.body);
1852
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001853 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001854 builder.setBuildPoint(&blocks.body);
1855 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001856 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001857 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001858 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001859
1860 builder.setBuildPoint(&blocks.continue_target);
1861 if (node->getTerminal())
1862 node->getTerminal()->traverse(this);
1863 if (node->getTest()) {
1864 node->getTest()->traverse(this);
1865 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001866 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001867 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001868 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001869 // TODO: unless there was a break/return/discard instruction
1870 // somewhere in the body, this is an infinite loop, so we should
1871 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001872 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001873 }
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001875 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001876 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001877 return false;
1878}
1879
1880bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1881{
1882 if (node->getExpression())
1883 node->getExpression()->traverse(this);
1884
1885 switch (node->getFlowOp()) {
1886 case glslang::EOpKill:
1887 builder.makeDiscard();
1888 break;
1889 case glslang::EOpBreak:
1890 if (breakForLoop.top())
1891 builder.createLoopExit();
1892 else
1893 builder.addSwitchBreak();
1894 break;
1895 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001896 builder.createLoopContinue();
1897 break;
1898 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001899 if (node->getExpression()) {
1900 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1901 spv::Id returnId = accessChainLoad(glslangReturnType);
1902 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1903 builder.clearAccessChain();
1904 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1905 builder.setAccessChainLValue(copyId);
1906 multiTypeStore(glslangReturnType, returnId);
1907 returnId = builder.createLoad(copyId);
1908 }
1909 builder.makeReturn(false, returnId);
1910 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001911 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001912
1913 builder.clearAccessChain();
1914 break;
1915
1916 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001917 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001918 break;
1919 }
1920
1921 return false;
1922}
1923
1924spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1925{
qining25262b32016-05-06 17:25:16 -04001926 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001927 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001928 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001929 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001930 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001931 }
1932
1933 // Now, handle actual variables
1934 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1935 spv::Id spvType = convertGlslangToSpvType(node->getType());
1936
1937 const char* name = node->getName().c_str();
1938 if (glslang::IsAnonymous(name))
1939 name = "";
1940
1941 return builder.createVariable(storageClass, spvType, name);
1942}
1943
1944// Return type Id of the sampled type.
1945spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1946{
1947 switch (sampler.type) {
1948 case glslang::EbtFloat: return builder.makeFloatType(32);
1949 case glslang::EbtInt: return builder.makeIntType(32);
1950 case glslang::EbtUint: return builder.makeUintType(32);
1951 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001952 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001953 return builder.makeFloatType(32);
1954 }
1955}
1956
John Kessenich8c8505c2016-07-26 12:50:38 -06001957// If node is a swizzle operation, return the type that should be used if
1958// the swizzle base is first consumed by another operation, before the swizzle
1959// is applied.
1960spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1961{
John Kessenichecba76f2017-01-06 00:34:48 -07001962 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001963 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1964 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1965 else
1966 return spv::NoType;
1967}
1968
1969// When inverting a swizzle with a parent op, this function
1970// will apply the swizzle operation to a completed parent operation.
1971spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1972{
1973 std::vector<unsigned> swizzle;
1974 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1975 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1976}
1977
John Kessenich8c8505c2016-07-26 12:50:38 -06001978// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1979void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1980{
1981 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1982 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1983 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1984}
1985
John Kessenich3ac051e2015-12-20 11:29:16 -07001986// Convert from a glslang type to an SPV type, by calling into a
1987// recursive version of this function. This establishes the inherited
1988// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001989spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1990{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001991 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001992}
1993
1994// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001995// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001996// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001997spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001998{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001999 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002000
2001 switch (type.getBasicType()) {
2002 case glslang::EbtVoid:
2003 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002004 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002005 break;
2006 case glslang::EbtFloat:
2007 spvType = builder.makeFloatType(32);
2008 break;
2009 case glslang::EbtDouble:
2010 spvType = builder.makeFloatType(64);
2011 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002012#ifdef AMD_EXTENSIONS
2013 case glslang::EbtFloat16:
2014 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2015 builder.addCapability(spv::CapabilityFloat16);
2016 spvType = builder.makeFloatType(16);
2017 break;
2018#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002019 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002020 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2021 // a 32-bit int where non-0 means true.
2022 if (explicitLayout != glslang::ElpNone)
2023 spvType = builder.makeUintType(32);
2024 else
2025 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002026 break;
2027 case glslang::EbtInt:
2028 spvType = builder.makeIntType(32);
2029 break;
2030 case glslang::EbtUint:
2031 spvType = builder.makeUintType(32);
2032 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002033 case glslang::EbtInt64:
2034 builder.addCapability(spv::CapabilityInt64);
2035 spvType = builder.makeIntType(64);
2036 break;
2037 case glslang::EbtUint64:
2038 builder.addCapability(spv::CapabilityInt64);
2039 spvType = builder.makeUintType(64);
2040 break;
John Kessenich426394d2015-07-23 10:22:48 -06002041 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002042 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002043 spvType = builder.makeUintType(32);
2044 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002045 case glslang::EbtSampler:
2046 {
2047 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002048 if (sampler.sampler) {
2049 // pure sampler
2050 spvType = builder.makeSamplerType();
2051 } else {
2052 // an image is present, make its type
2053 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2054 sampler.image ? 2 : 1, TranslateImageFormat(type));
2055 if (sampler.combined) {
2056 // already has both image and sampler, make the combined type
2057 spvType = builder.makeSampledImageType(spvType);
2058 }
John Kessenich55e7d112015-11-15 21:33:39 -07002059 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002060 }
John Kessenich140f3df2015-06-26 16:58:36 -06002061 break;
2062 case glslang::EbtStruct:
2063 case glslang::EbtBlock:
2064 {
2065 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002066 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002067
2068 // Try to share structs for different layouts, but not yet for other
2069 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002070 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002071 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002072 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002073 break;
2074
2075 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002076 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002077 memberRemapper[glslangMembers].resize(glslangMembers->size());
2078 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 }
2080 break;
2081 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002082 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002083 break;
2084 }
2085
2086 if (type.isMatrix())
2087 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2088 else {
2089 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2090 if (type.getVectorSize() > 1)
2091 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2092 }
2093
2094 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002095 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2096
John Kessenichc9a80832015-09-12 12:17:44 -06002097 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002098 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002099 // We need to decorate array strides for types needing explicit layout, except blocks.
2100 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002101 // Use a dummy glslang type for querying internal strides of
2102 // arrays of arrays, but using just a one-dimensional array.
2103 glslang::TType simpleArrayType(type, 0); // deference type of the array
2104 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2105 simpleArrayType.getArraySizes().dereference();
2106
2107 // Will compute the higher-order strides here, rather than making a whole
2108 // pile of types and doing repetitive recursion on their contents.
2109 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2110 }
John Kessenichf8842e52016-01-04 19:22:56 -07002111
2112 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002113 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002114 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002115 if (stride > 0)
2116 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002117 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002118 }
2119 } else {
2120 // single-dimensional array, and don't yet have stride
2121
John Kessenichf8842e52016-01-04 19:22:56 -07002122 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002123 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2124 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002125 }
John Kessenich31ed4832015-09-09 17:51:38 -06002126
John Kessenichc9a80832015-09-12 12:17:44 -06002127 // Do the outer dimension, which might not be known for a runtime-sized array
2128 if (type.isRuntimeSizedArray()) {
2129 spvType = builder.makeRuntimeArray(spvType);
2130 } else {
2131 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002132 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002133 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002134 if (stride > 0)
2135 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002136 }
2137
2138 return spvType;
2139}
2140
John Kessenich6090df02016-06-30 21:18:02 -06002141// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2142// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2143// Mutually recursive with convertGlslangToSpvType().
2144spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2145 const glslang::TTypeList* glslangMembers,
2146 glslang::TLayoutPacking explicitLayout,
2147 const glslang::TQualifier& qualifier)
2148{
2149 // Create a vector of struct types for SPIR-V to consume
2150 std::vector<spv::Id> spvMembers;
2151 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2152 int locationOffset = 0; // for use across struct members, when they are called recursively
2153 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2154 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2155 if (glslangMember.hiddenMember()) {
2156 ++memberDelta;
2157 if (type.getBasicType() == glslang::EbtBlock)
2158 memberRemapper[glslangMembers][i] = -1;
2159 } else {
2160 if (type.getBasicType() == glslang::EbtBlock)
2161 memberRemapper[glslangMembers][i] = i - memberDelta;
2162 // modify just this child's view of the qualifier
2163 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2164 InheritQualifiers(memberQualifier, qualifier);
2165
2166 // manually inherit location; it's more complex
2167 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2168 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2169 if (qualifier.hasLocation())
2170 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2171
2172 // recurse
2173 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2174 }
2175 }
2176
2177 // Make the SPIR-V type
2178 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002179 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002180 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2181
2182 // Decorate it
2183 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2184
2185 return spvType;
2186}
2187
2188void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2189 const glslang::TTypeList* glslangMembers,
2190 glslang::TLayoutPacking explicitLayout,
2191 const glslang::TQualifier& qualifier,
2192 spv::Id spvType)
2193{
2194 // Name and decorate the non-hidden members
2195 int offset = -1;
2196 int locationOffset = 0; // for use within the members of this struct
2197 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2198 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2199 int member = i;
2200 if (type.getBasicType() == glslang::EbtBlock)
2201 member = memberRemapper[glslangMembers][i];
2202
2203 // modify just this child's view of the qualifier
2204 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2205 InheritQualifiers(memberQualifier, qualifier);
2206
2207 // using -1 above to indicate a hidden member
2208 if (member >= 0) {
2209 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2210 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2211 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2212 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2213 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2214 if (type.getBasicType() == glslang::EbtBlock) {
2215 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2216 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2217 }
2218 }
2219 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2220
2221 if (qualifier.storage == glslang::EvqBuffer) {
2222 std::vector<spv::Decoration> memory;
2223 TranslateMemoryDecoration(memberQualifier, memory);
2224 for (unsigned int i = 0; i < memory.size(); ++i)
2225 addMemberDecoration(spvType, member, memory[i]);
2226 }
2227
John Kessenich2f47bc92016-06-30 21:47:35 -06002228 // Compute location decoration; tricky based on whether inheritance is at play and
2229 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002230 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2231 // probably move to the linker stage of the front end proper, and just have the
2232 // answer sitting already distributed throughout the individual member locations.
2233 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002234 // Ignore member locations if the container is an array, as that's
2235 // ill-specified and decisions have been made to not allow this anyway.
2236 // The object itself must have a location, and that comes out from decorating the object,
2237 // not the type (this code decorates types).
2238 if (! type.isArray()) {
2239 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2240 // struct members should not have explicit locations
2241 assert(type.getBasicType() != glslang::EbtStruct);
2242 location = memberQualifier.layoutLocation;
2243 } else if (type.getBasicType() != glslang::EbtBlock) {
2244 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2245 // The members, and their nested types, must not themselves have Location decorations.
2246 } else if (qualifier.hasLocation()) // inheritance
2247 location = qualifier.layoutLocation + locationOffset;
2248 }
John Kessenich6090df02016-06-30 21:18:02 -06002249 if (location >= 0)
2250 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2251
John Kessenich2f47bc92016-06-30 21:47:35 -06002252 if (qualifier.hasLocation()) // track for upcoming inheritance
2253 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2254
John Kessenich6090df02016-06-30 21:18:02 -06002255 // component, XFB, others
2256 if (glslangMember.getQualifier().hasComponent())
2257 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2258 if (glslangMember.getQualifier().hasXfbOffset())
2259 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2260 else if (explicitLayout != glslang::ElpNone) {
2261 // figure out what to do with offset, which is accumulating
2262 int nextOffset;
2263 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2264 if (offset >= 0)
2265 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2266 offset = nextOffset;
2267 }
2268
2269 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2270 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2271
2272 // built-in variable decorations
2273 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002274 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002275 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2276 }
2277 }
2278
2279 // Decorate the structure
2280 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2281 addDecoration(spvType, TranslateBlockDecoration(type));
2282 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2283 builder.addCapability(spv::CapabilityGeometryStreams);
2284 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2285 }
2286 if (glslangIntermediate->getXfbMode()) {
2287 builder.addCapability(spv::CapabilityTransformFeedback);
2288 if (type.getQualifier().hasXfbStride())
2289 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2290 if (type.getQualifier().hasXfbBuffer())
2291 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2292 }
2293}
2294
John Kessenich6c292d32016-02-15 20:58:50 -07002295// Turn the expression forming the array size into an id.
2296// This is not quite trivial, because of specialization constants.
2297// Sometimes, a raw constant is turned into an Id, and sometimes
2298// a specialization constant expression is.
2299spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2300{
2301 // First, see if this is sized with a node, meaning a specialization constant:
2302 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2303 if (specNode != nullptr) {
2304 builder.clearAccessChain();
2305 specNode->traverse(this);
2306 return accessChainLoad(specNode->getAsTyped()->getType());
2307 }
qining25262b32016-05-06 17:25:16 -04002308
John Kessenich6c292d32016-02-15 20:58:50 -07002309 // Otherwise, need a compile-time (front end) size, get it:
2310 int size = arraySizes.getDimSize(dim);
2311 assert(size > 0);
2312 return builder.makeUintConstant(size);
2313}
2314
John Kessenich103bef92016-02-08 21:38:15 -07002315// Wrap the builder's accessChainLoad to:
2316// - localize handling of RelaxedPrecision
2317// - use the SPIR-V inferred type instead of another conversion of the glslang type
2318// (avoids unnecessary work and possible type punning for structures)
2319// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002320spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2321{
John Kessenich103bef92016-02-08 21:38:15 -07002322 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2323 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2324
2325 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002326 if (type.getBasicType() == glslang::EbtBool) {
2327 if (builder.isScalarType(nominalTypeId)) {
2328 // Conversion for bool
2329 spv::Id boolType = builder.makeBoolType();
2330 if (nominalTypeId != boolType)
2331 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2332 } else if (builder.isVectorType(nominalTypeId)) {
2333 // Conversion for bvec
2334 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2335 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2336 if (nominalTypeId != bvecType)
2337 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2338 }
2339 }
John Kessenich103bef92016-02-08 21:38:15 -07002340
2341 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002342}
2343
Rex Xu27253232016-02-23 17:51:09 +08002344// Wrap the builder's accessChainStore to:
2345// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002346//
2347// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002348void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2349{
2350 // Need to convert to abstract types when necessary
2351 if (type.getBasicType() == glslang::EbtBool) {
2352 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2353
2354 if (builder.isScalarType(nominalTypeId)) {
2355 // Conversion for bool
2356 spv::Id boolType = builder.makeBoolType();
2357 if (nominalTypeId != boolType) {
2358 spv::Id zero = builder.makeUintConstant(0);
2359 spv::Id one = builder.makeUintConstant(1);
2360 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2361 }
2362 } else if (builder.isVectorType(nominalTypeId)) {
2363 // Conversion for bvec
2364 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2365 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2366 if (nominalTypeId != bvecType) {
2367 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2368 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2369 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2370 }
2371 }
2372 }
2373
2374 builder.accessChainStore(rvalue);
2375}
2376
John Kessenich4bf71552016-09-02 11:20:21 -06002377// For storing when types match at the glslang level, but not might match at the
2378// SPIR-V level.
2379//
2380// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002381// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002382// as in a member-decorated way.
2383//
2384// NOTE: This function can handle any store request; if it's not special it
2385// simplifies to a simple OpStore.
2386//
2387// Implicitly uses the existing builder.accessChain as the storage target.
2388void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2389{
John Kessenichb3e24e42016-09-11 12:33:43 -06002390 // we only do the complex path here if it's an aggregate
2391 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002392 accessChainStore(type, rValue);
2393 return;
2394 }
2395
John Kessenichb3e24e42016-09-11 12:33:43 -06002396 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002397 spv::Id rType = builder.getTypeId(rValue);
2398 spv::Id lValue = builder.accessChainGetLValue();
2399 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2400 if (lType == rType) {
2401 accessChainStore(type, rValue);
2402 return;
2403 }
2404
John Kessenichb3e24e42016-09-11 12:33:43 -06002405 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002406 // where the two types were the same type in GLSL. This requires member
2407 // by member copy, recursively.
2408
John Kessenichb3e24e42016-09-11 12:33:43 -06002409 // If an array, copy element by element.
2410 if (type.isArray()) {
2411 glslang::TType glslangElementType(type, 0);
2412 spv::Id elementRType = builder.getContainedTypeId(rType);
2413 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2414 // get the source member
2415 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002416
John Kessenichb3e24e42016-09-11 12:33:43 -06002417 // set up the target storage
2418 builder.clearAccessChain();
2419 builder.setAccessChainLValue(lValue);
2420 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002421
John Kessenichb3e24e42016-09-11 12:33:43 -06002422 // store the member
2423 multiTypeStore(glslangElementType, elementRValue);
2424 }
2425 } else {
2426 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002427
John Kessenichb3e24e42016-09-11 12:33:43 -06002428 // loop over structure members
2429 const glslang::TTypeList& members = *type.getStruct();
2430 for (int m = 0; m < (int)members.size(); ++m) {
2431 const glslang::TType& glslangMemberType = *members[m].type;
2432
2433 // get the source member
2434 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2435 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2436
2437 // set up the target storage
2438 builder.clearAccessChain();
2439 builder.setAccessChainLValue(lValue);
2440 builder.accessChainPush(builder.makeIntConstant(m));
2441
2442 // store the member
2443 multiTypeStore(glslangMemberType, memberRValue);
2444 }
John Kessenich4bf71552016-09-02 11:20:21 -06002445 }
2446}
2447
John Kessenichf85e8062015-12-19 13:57:10 -07002448// Decide whether or not this type should be
2449// decorated with offsets and strides, and if so
2450// whether std140 or std430 rules should be applied.
2451glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002452{
John Kessenichf85e8062015-12-19 13:57:10 -07002453 // has to be a block
2454 if (type.getBasicType() != glslang::EbtBlock)
2455 return glslang::ElpNone;
2456
2457 // has to be a uniform or buffer block
2458 if (type.getQualifier().storage != glslang::EvqUniform &&
2459 type.getQualifier().storage != glslang::EvqBuffer)
2460 return glslang::ElpNone;
2461
2462 // return the layout to use
2463 switch (type.getQualifier().layoutPacking) {
2464 case glslang::ElpStd140:
2465 case glslang::ElpStd430:
2466 return type.getQualifier().layoutPacking;
2467 default:
2468 return glslang::ElpNone;
2469 }
John Kessenich31ed4832015-09-09 17:51:38 -06002470}
2471
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002472// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002473int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002474{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002475 int size;
John Kessenich49987892015-12-29 17:11:44 -07002476 int stride;
2477 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002478
2479 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002480}
2481
John Kessenich49987892015-12-29 17:11:44 -07002482// 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 -07002483// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002484int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002485{
John Kessenich49987892015-12-29 17:11:44 -07002486 glslang::TType elementType;
2487 elementType.shallowCopy(matrixType);
2488 elementType.clearArraySizes();
2489
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002490 int size;
John Kessenich49987892015-12-29 17:11:44 -07002491 int stride;
2492 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2493
2494 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002495}
2496
John Kessenich5e4b1242015-08-06 22:53:06 -06002497// Given a member type of a struct, realign the current offset for it, and compute
2498// the next (not yet aligned) offset for the next member, which will get aligned
2499// on the next call.
2500// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2501// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2502// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002503void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002504 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002505{
2506 // this will get a positive value when deemed necessary
2507 nextOffset = -1;
2508
John Kessenich5e4b1242015-08-06 22:53:06 -06002509 // override anything in currentOffset with user-set offset
2510 if (memberType.getQualifier().hasOffset())
2511 currentOffset = memberType.getQualifier().layoutOffset;
2512
2513 // It could be that current linker usage in glslang updated all the layoutOffset,
2514 // in which case the following code does not matter. But, that's not quite right
2515 // once cross-compilation unit GLSL validation is done, as the original user
2516 // settings are needed in layoutOffset, and then the following will come into play.
2517
John Kessenichf85e8062015-12-19 13:57:10 -07002518 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002519 if (! memberType.getQualifier().hasOffset())
2520 currentOffset = -1;
2521
2522 return;
2523 }
2524
John Kessenichf85e8062015-12-19 13:57:10 -07002525 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002526 if (currentOffset < 0)
2527 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002528
John Kessenich5e4b1242015-08-06 22:53:06 -06002529 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2530 // but possibly not yet correctly aligned.
2531
2532 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002533 int dummyStride;
2534 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002535 glslang::RoundToPow2(currentOffset, memberAlignment);
2536 nextOffset = currentOffset + memberSize;
2537}
2538
David Netoa901ffe2016-06-08 14:11:40 +01002539void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002540{
David Netoa901ffe2016-06-08 14:11:40 +01002541 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2542 switch (glslangBuiltIn)
2543 {
2544 case glslang::EbvClipDistance:
2545 case glslang::EbvCullDistance:
2546 case glslang::EbvPointSize:
2547 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2548 // Alternately, we could just call this for any glslang built-in, since the
2549 // capability already guards against duplicates.
2550 TranslateBuiltInDecoration(glslangBuiltIn, false);
2551 break;
2552 default:
2553 // Capabilities were already generated when the struct was declared.
2554 break;
2555 }
John Kessenichebb50532016-05-16 19:22:05 -06002556}
2557
John Kessenich6fccb3c2016-09-19 16:01:41 -06002558bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002559{
John Kessenicheee9d532016-09-19 18:09:30 -06002560 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002561}
2562
2563// Make all the functions, skeletally, without actually visiting their bodies.
2564void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2565{
2566 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2567 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002568 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002569 continue;
2570
2571 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002572 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002573 //
qining25262b32016-05-06 17:25:16 -04002574 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002575 // function. What it is an address of varies:
2576 //
John Kessenich4bf71552016-09-02 11:20:21 -06002577 // - "in" parameters not marked as "const" can be written to without modifying the calling
2578 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002579 //
2580 // - "const in" parameters can just be the r-value, as no writes need occur.
2581 //
John Kessenich4bf71552016-09-02 11:20:21 -06002582 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2583 // 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 -06002584
2585 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002586 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002587 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2588
2589 for (int p = 0; p < (int)parameters.size(); ++p) {
2590 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2591 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002592 if (paramType.isOpaque())
2593 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2594 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002595 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2596 else
John Kessenich4bf71552016-09-02 11:20:21 -06002597 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002598 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002599 paramTypes.push_back(typeId);
2600 }
2601
2602 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002603 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2604 convertGlslangToSpvType(glslFunction->getType()),
2605 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 // Track function to emit/call later
2608 functionMap[glslFunction->getName().c_str()] = function;
2609
2610 // Set the parameter id's
2611 for (int p = 0; p < (int)parameters.size(); ++p) {
2612 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2613 // give a name too
2614 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2615 }
2616 }
2617}
2618
2619// Process all the initializers, while skipping the functions and link objects
2620void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2621{
2622 builder.setBuildPoint(shaderEntry->getLastBlock());
2623 for (int i = 0; i < (int)initializers.size(); ++i) {
2624 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2625 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2626
2627 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002628 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002629 initializer->traverse(this);
2630 }
2631 }
2632}
2633
2634// Process all the functions, while skipping initializers.
2635void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2636{
2637 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2638 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002639 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002640 node->traverse(this);
2641 }
2642}
2643
2644void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2645{
qining25262b32016-05-06 17:25:16 -04002646 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002647 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002648 currentFunction = functionMap[node->getName().c_str()];
2649 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002650 builder.setBuildPoint(functionBlock);
2651}
2652
Rex Xu04db3f52015-09-16 11:44:02 +08002653void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002654{
Rex Xufc618912015-09-09 16:42:49 +08002655 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002656
2657 glslang::TSampler sampler = {};
2658 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002659 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002660 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2661 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2662 }
2663
John Kessenich140f3df2015-06-26 16:58:36 -06002664 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2665 builder.clearAccessChain();
2666 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002667
2668 // Special case l-value operands
2669 bool lvalue = false;
2670 switch (node.getOp()) {
2671 case glslang::EOpImageAtomicAdd:
2672 case glslang::EOpImageAtomicMin:
2673 case glslang::EOpImageAtomicMax:
2674 case glslang::EOpImageAtomicAnd:
2675 case glslang::EOpImageAtomicOr:
2676 case glslang::EOpImageAtomicXor:
2677 case glslang::EOpImageAtomicExchange:
2678 case glslang::EOpImageAtomicCompSwap:
2679 if (i == 0)
2680 lvalue = true;
2681 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002682 case glslang::EOpSparseImageLoad:
2683 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2684 lvalue = true;
2685 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002686 case glslang::EOpSparseTexture:
2687 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2688 lvalue = true;
2689 break;
2690 case glslang::EOpSparseTextureClamp:
2691 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2692 lvalue = true;
2693 break;
2694 case glslang::EOpSparseTextureLod:
2695 case glslang::EOpSparseTextureOffset:
2696 if (i == 3)
2697 lvalue = true;
2698 break;
2699 case glslang::EOpSparseTextureFetch:
2700 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2701 lvalue = true;
2702 break;
2703 case glslang::EOpSparseTextureFetchOffset:
2704 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2705 lvalue = true;
2706 break;
2707 case glslang::EOpSparseTextureLodOffset:
2708 case glslang::EOpSparseTextureGrad:
2709 case glslang::EOpSparseTextureOffsetClamp:
2710 if (i == 4)
2711 lvalue = true;
2712 break;
2713 case glslang::EOpSparseTextureGradOffset:
2714 case glslang::EOpSparseTextureGradClamp:
2715 if (i == 5)
2716 lvalue = true;
2717 break;
2718 case glslang::EOpSparseTextureGradOffsetClamp:
2719 if (i == 6)
2720 lvalue = true;
2721 break;
2722 case glslang::EOpSparseTextureGather:
2723 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2724 lvalue = true;
2725 break;
2726 case glslang::EOpSparseTextureGatherOffset:
2727 case glslang::EOpSparseTextureGatherOffsets:
2728 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2729 lvalue = true;
2730 break;
Rex Xufc618912015-09-09 16:42:49 +08002731 default:
2732 break;
2733 }
2734
Rex Xu6b86d492015-09-16 17:48:22 +08002735 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002736 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002737 else
John Kessenich32cfd492016-02-02 12:37:46 -07002738 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002739 }
2740}
2741
John Kessenichfc51d282015-08-19 13:34:18 -06002742void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002743{
John Kessenichfc51d282015-08-19 13:34:18 -06002744 builder.clearAccessChain();
2745 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002746 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002747}
John Kessenich140f3df2015-06-26 16:58:36 -06002748
John Kessenichfc51d282015-08-19 13:34:18 -06002749spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2750{
Rex Xufc618912015-09-09 16:42:49 +08002751 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002752 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002753 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002754 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002755
John Kessenichfc51d282015-08-19 13:34:18 -06002756 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002757 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2758 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2759 std::vector<spv::Id> arguments;
2760 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002761 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002762 else
2763 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002764 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002765
2766 spv::Builder::TextureParameters params = { };
2767 params.sampler = arguments[0];
2768
Rex Xu04db3f52015-09-16 11:44:02 +08002769 glslang::TCrackedTextureOp cracked;
2770 node->crackTexture(sampler, cracked);
2771
John Kessenichfc51d282015-08-19 13:34:18 -06002772 // Check for queries
2773 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002774 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2775 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002776 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002777
John Kessenichfc51d282015-08-19 13:34:18 -06002778 switch (node->getOp()) {
2779 case glslang::EOpImageQuerySize:
2780 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002781 if (arguments.size() > 1) {
2782 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002783 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002784 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002786 case glslang::EOpImageQuerySamples:
2787 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002788 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002789 case glslang::EOpTextureQueryLod:
2790 params.coords = arguments[1];
2791 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2792 case glslang::EOpTextureQueryLevels:
2793 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002794 case glslang::EOpSparseTexelsResident:
2795 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002796 default:
2797 assert(0);
2798 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002799 }
John Kessenich140f3df2015-06-26 16:58:36 -06002800 }
2801
Rex Xufc618912015-09-09 16:42:49 +08002802 // Check for image functions other than queries
2803 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002804 std::vector<spv::Id> operands;
2805 auto opIt = arguments.begin();
2806 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002807
2808 // Handle subpass operations
2809 // TODO: GLSL should change to have the "MS" only on the type rather than the
2810 // built-in function.
2811 if (cracked.subpass) {
2812 // add on the (0,0) coordinate
2813 spv::Id zero = builder.makeIntConstant(0);
2814 std::vector<spv::Id> comps;
2815 comps.push_back(zero);
2816 comps.push_back(zero);
2817 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2818 if (sampler.ms) {
2819 operands.push_back(spv::ImageOperandsSampleMask);
2820 operands.push_back(*(opIt++));
2821 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002822 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002823 }
2824
John Kessenich56bab042015-09-16 10:54:31 -06002825 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002826 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002827 if (sampler.ms) {
2828 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002829 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002830 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002831 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2832 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002833 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002834 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002835 if (sampler.ms) {
2836 operands.push_back(*(opIt + 1));
2837 operands.push_back(spv::ImageOperandsSampleMask);
2838 operands.push_back(*opIt);
2839 } else
2840 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002841 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002842 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2843 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002844 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002845 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2846 builder.addCapability(spv::CapabilitySparseResidency);
2847 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2848 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2849
2850 if (sampler.ms) {
2851 operands.push_back(spv::ImageOperandsSampleMask);
2852 operands.push_back(*opIt++);
2853 }
2854
2855 // Create the return type that was a special structure
2856 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002857 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002858 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2859 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2860
2861 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2862
2863 // Decode the return type
2864 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2865 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002866 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002867 // Process image atomic operations
2868
2869 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2870 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002871 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002872
John Kessenich8c8505c2016-07-26 12:50:38 -06002873 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002874 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002875
2876 std::vector<spv::Id> operands;
2877 operands.push_back(pointer);
2878 for (; opIt != arguments.end(); ++opIt)
2879 operands.push_back(*opIt);
2880
John Kessenich8c8505c2016-07-26 12:50:38 -06002881 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002882 }
2883 }
2884
2885 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002886 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002887 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2888
John Kessenichfc51d282015-08-19 13:34:18 -06002889 // check for bias argument
2890 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002891 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002892 int nonBiasArgCount = 2;
2893 if (cracked.offset)
2894 ++nonBiasArgCount;
2895 if (cracked.grad)
2896 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002897 if (cracked.lodClamp)
2898 ++nonBiasArgCount;
2899 if (sparse)
2900 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002901
2902 if ((int)arguments.size() > nonBiasArgCount)
2903 bias = true;
2904 }
2905
John Kessenicha5c33d62016-06-02 23:45:21 -06002906 // See if the sampler param should really be just the SPV image part
2907 if (cracked.fetch) {
2908 // a fetch needs to have the image extracted first
2909 if (builder.isSampledImage(params.sampler))
2910 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2911 }
2912
John Kessenichfc51d282015-08-19 13:34:18 -06002913 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002914
John Kessenichfc51d282015-08-19 13:34:18 -06002915 params.coords = arguments[1];
2916 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002917 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002918
2919 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002920 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002921 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002922 ++extraArgs;
2923 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002924 params.Dref = arguments[2];
2925 ++extraArgs;
2926 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002927 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002928 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002929 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002930 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002931 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002932 dRefComp = builder.getNumComponents(params.coords) - 1;
2933 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002934 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2935 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002936
2937 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002938 if (cracked.lod) {
2939 params.lod = arguments[2];
2940 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002941 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2942 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2943 noImplicitLod = true;
2944 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002945
2946 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002947 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002948 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002949 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002950 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002951
2952 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002953 if (cracked.grad) {
2954 params.gradX = arguments[2 + extraArgs];
2955 params.gradY = arguments[3 + extraArgs];
2956 extraArgs += 2;
2957 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002958
2959 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002960 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002961 params.offset = arguments[2 + extraArgs];
2962 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002963 } else if (cracked.offsets) {
2964 params.offsets = arguments[2 + extraArgs];
2965 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002966 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002967
2968 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002969 if (cracked.lodClamp) {
2970 params.lodClamp = arguments[2 + extraArgs];
2971 ++extraArgs;
2972 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002973
2974 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002975 if (sparse) {
2976 params.texelOut = arguments[2 + extraArgs];
2977 ++extraArgs;
2978 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002979
2980 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002981 if (bias) {
2982 params.bias = arguments[2 + extraArgs];
2983 ++extraArgs;
2984 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002985
2986 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002987 if (cracked.gather && ! sampler.shadow) {
2988 // default component is 0, if missing, otherwise an argument
2989 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002990 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002991 ++extraArgs;
2992 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002993 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002994 }
2995 }
John Kessenichfc51d282015-08-19 13:34:18 -06002996
John Kessenich65336482016-06-16 14:06:26 -06002997 // projective component (might not to move)
2998 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2999 // are divided by the last component of P."
3000 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3001 // unused components will appear after all used components."
3002 if (cracked.proj) {
3003 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3004 int projTargetComp;
3005 switch (sampler.dim) {
3006 case glslang::Esd1D: projTargetComp = 1; break;
3007 case glslang::Esd2D: projTargetComp = 2; break;
3008 case glslang::EsdRect: projTargetComp = 2; break;
3009 default: projTargetComp = projSourceComp; break;
3010 }
3011 // copy the projective coordinate if we have to
3012 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003013 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003014 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3015 projSourceComp);
3016 params.coords = builder.createCompositeInsert(projComp, params.coords,
3017 builder.getTypeId(params.coords), projTargetComp);
3018 }
3019 }
3020
John Kessenich8c8505c2016-07-26 12:50:38 -06003021 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003022}
3023
3024spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3025{
3026 // Grab the function's pointer from the previously created function
3027 spv::Function* function = functionMap[node->getName().c_str()];
3028 if (! function)
3029 return 0;
3030
3031 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3032 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3033
3034 // See comments in makeFunctions() for details about the semantics for parameter passing.
3035 //
3036 // These imply we need a four step process:
3037 // 1. Evaluate the arguments
3038 // 2. Allocate and make copies of in, out, and inout arguments
3039 // 3. Make the call
3040 // 4. Copy back the results
3041
3042 // 1. Evaluate the arguments
3043 std::vector<spv::Builder::AccessChain> lValues;
3044 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003045 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003046 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003047 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003048 // build l-value
3049 builder.clearAccessChain();
3050 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003051 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003052 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003053 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003054 // save l-value
3055 lValues.push_back(builder.getAccessChain());
3056 } else {
3057 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003058 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003059 }
3060 }
3061
3062 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3063 // copy the original into that space.
3064 //
3065 // Also, build up the list of actual arguments to pass in for the call
3066 int lValueCount = 0;
3067 int rValueCount = 0;
3068 std::vector<spv::Id> spvArgs;
3069 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003070 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003071 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003072 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003073 builder.setAccessChain(lValues[lValueCount]);
3074 arg = builder.accessChainGetLValue();
3075 ++lValueCount;
3076 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003077 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003078 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3079 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3080 // need to copy the input into output space
3081 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003082 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003083 builder.clearAccessChain();
3084 builder.setAccessChainLValue(arg);
3085 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003086 }
3087 ++lValueCount;
3088 } else {
3089 arg = rValues[rValueCount];
3090 ++rValueCount;
3091 }
3092 spvArgs.push_back(arg);
3093 }
3094
3095 // 3. Make the call.
3096 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003097 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003098
3099 // 4. Copy back out an "out" arguments.
3100 lValueCount = 0;
3101 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003102 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003103 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3104 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3105 spv::Id copy = builder.createLoad(spvArgs[a]);
3106 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003107 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003108 }
3109 ++lValueCount;
3110 }
3111 }
3112
3113 return result;
3114}
3115
3116// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003117spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3118 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003119 spv::Id typeId, spv::Id left, spv::Id right,
3120 glslang::TBasicType typeProxy, bool reduceComparison)
3121{
Rex Xu8ff43de2016-04-22 16:51:45 +08003122 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003123#ifdef AMD_EXTENSIONS
3124 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3125#else
John Kessenich140f3df2015-06-26 16:58:36 -06003126 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003127#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003128 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003129
3130 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003131 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003132 bool comparison = false;
3133
3134 switch (op) {
3135 case glslang::EOpAdd:
3136 case glslang::EOpAddAssign:
3137 if (isFloat)
3138 binOp = spv::OpFAdd;
3139 else
3140 binOp = spv::OpIAdd;
3141 break;
3142 case glslang::EOpSub:
3143 case glslang::EOpSubAssign:
3144 if (isFloat)
3145 binOp = spv::OpFSub;
3146 else
3147 binOp = spv::OpISub;
3148 break;
3149 case glslang::EOpMul:
3150 case glslang::EOpMulAssign:
3151 if (isFloat)
3152 binOp = spv::OpFMul;
3153 else
3154 binOp = spv::OpIMul;
3155 break;
3156 case glslang::EOpVectorTimesScalar:
3157 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003158 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003159 if (builder.isVector(right))
3160 std::swap(left, right);
3161 assert(builder.isScalar(right));
3162 needMatchingVectors = false;
3163 binOp = spv::OpVectorTimesScalar;
3164 } else
3165 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpVectorTimesMatrix:
3168 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003169 binOp = spv::OpVectorTimesMatrix;
3170 break;
3171 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003172 binOp = spv::OpMatrixTimesVector;
3173 break;
3174 case glslang::EOpMatrixTimesScalar:
3175 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003176 binOp = spv::OpMatrixTimesScalar;
3177 break;
3178 case glslang::EOpMatrixTimesMatrix:
3179 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003180 binOp = spv::OpMatrixTimesMatrix;
3181 break;
3182 case glslang::EOpOuterProduct:
3183 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003184 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 break;
3186
3187 case glslang::EOpDiv:
3188 case glslang::EOpDivAssign:
3189 if (isFloat)
3190 binOp = spv::OpFDiv;
3191 else if (isUnsigned)
3192 binOp = spv::OpUDiv;
3193 else
3194 binOp = spv::OpSDiv;
3195 break;
3196 case glslang::EOpMod:
3197 case glslang::EOpModAssign:
3198 if (isFloat)
3199 binOp = spv::OpFMod;
3200 else if (isUnsigned)
3201 binOp = spv::OpUMod;
3202 else
3203 binOp = spv::OpSMod;
3204 break;
3205 case glslang::EOpRightShift:
3206 case glslang::EOpRightShiftAssign:
3207 if (isUnsigned)
3208 binOp = spv::OpShiftRightLogical;
3209 else
3210 binOp = spv::OpShiftRightArithmetic;
3211 break;
3212 case glslang::EOpLeftShift:
3213 case glslang::EOpLeftShiftAssign:
3214 binOp = spv::OpShiftLeftLogical;
3215 break;
3216 case glslang::EOpAnd:
3217 case glslang::EOpAndAssign:
3218 binOp = spv::OpBitwiseAnd;
3219 break;
3220 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003221 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 binOp = spv::OpLogicalAnd;
3223 break;
3224 case glslang::EOpInclusiveOr:
3225 case glslang::EOpInclusiveOrAssign:
3226 binOp = spv::OpBitwiseOr;
3227 break;
3228 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003229 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003230 binOp = spv::OpLogicalOr;
3231 break;
3232 case glslang::EOpExclusiveOr:
3233 case glslang::EOpExclusiveOrAssign:
3234 binOp = spv::OpBitwiseXor;
3235 break;
3236 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003237 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003238 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003239 break;
3240
3241 case glslang::EOpLessThan:
3242 case glslang::EOpGreaterThan:
3243 case glslang::EOpLessThanEqual:
3244 case glslang::EOpGreaterThanEqual:
3245 case glslang::EOpEqual:
3246 case glslang::EOpNotEqual:
3247 case glslang::EOpVectorEqual:
3248 case glslang::EOpVectorNotEqual:
3249 comparison = true;
3250 break;
3251 default:
3252 break;
3253 }
3254
John Kessenich7c1aa102015-10-15 13:29:11 -06003255 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003256 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003257 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003258 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003259 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003260
3261 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003262 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003263 builder.promoteScalar(precision, left, right);
3264
qining25262b32016-05-06 17:25:16 -04003265 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3266 addDecoration(result, noContraction);
3267 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003268 }
3269
3270 if (! comparison)
3271 return 0;
3272
John Kessenich7c1aa102015-10-15 13:29:11 -06003273 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003274
John Kessenich4583b612016-08-07 19:14:22 -06003275 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3276 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003277 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003278
3279 switch (op) {
3280 case glslang::EOpLessThan:
3281 if (isFloat)
3282 binOp = spv::OpFOrdLessThan;
3283 else if (isUnsigned)
3284 binOp = spv::OpULessThan;
3285 else
3286 binOp = spv::OpSLessThan;
3287 break;
3288 case glslang::EOpGreaterThan:
3289 if (isFloat)
3290 binOp = spv::OpFOrdGreaterThan;
3291 else if (isUnsigned)
3292 binOp = spv::OpUGreaterThan;
3293 else
3294 binOp = spv::OpSGreaterThan;
3295 break;
3296 case glslang::EOpLessThanEqual:
3297 if (isFloat)
3298 binOp = spv::OpFOrdLessThanEqual;
3299 else if (isUnsigned)
3300 binOp = spv::OpULessThanEqual;
3301 else
3302 binOp = spv::OpSLessThanEqual;
3303 break;
3304 case glslang::EOpGreaterThanEqual:
3305 if (isFloat)
3306 binOp = spv::OpFOrdGreaterThanEqual;
3307 else if (isUnsigned)
3308 binOp = spv::OpUGreaterThanEqual;
3309 else
3310 binOp = spv::OpSGreaterThanEqual;
3311 break;
3312 case glslang::EOpEqual:
3313 case glslang::EOpVectorEqual:
3314 if (isFloat)
3315 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003316 else if (isBool)
3317 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 else
3319 binOp = spv::OpIEqual;
3320 break;
3321 case glslang::EOpNotEqual:
3322 case glslang::EOpVectorNotEqual:
3323 if (isFloat)
3324 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003325 else if (isBool)
3326 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003327 else
3328 binOp = spv::OpINotEqual;
3329 break;
3330 default:
3331 break;
3332 }
3333
qining25262b32016-05-06 17:25:16 -04003334 if (binOp != spv::OpNop) {
3335 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3336 addDecoration(result, noContraction);
3337 return builder.setPrecision(result, precision);
3338 }
John Kessenich140f3df2015-06-26 16:58:36 -06003339
3340 return 0;
3341}
3342
John Kessenich04bb8a02015-12-12 12:28:14 -07003343//
3344// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3345// These can be any of:
3346//
3347// matrix * scalar
3348// scalar * matrix
3349// matrix * matrix linear algebraic
3350// matrix * vector
3351// vector * matrix
3352// matrix * matrix componentwise
3353// matrix op matrix op in {+, -, /}
3354// matrix op scalar op in {+, -, /}
3355// scalar op matrix op in {+, -, /}
3356//
qining25262b32016-05-06 17:25:16 -04003357spv::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 -07003358{
3359 bool firstClass = true;
3360
3361 // First, handle first-class matrix operations (* and matrix/scalar)
3362 switch (op) {
3363 case spv::OpFDiv:
3364 if (builder.isMatrix(left) && builder.isScalar(right)) {
3365 // turn matrix / scalar into a multiply...
3366 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3367 op = spv::OpMatrixTimesScalar;
3368 } else
3369 firstClass = false;
3370 break;
3371 case spv::OpMatrixTimesScalar:
3372 if (builder.isMatrix(right))
3373 std::swap(left, right);
3374 assert(builder.isScalar(right));
3375 break;
3376 case spv::OpVectorTimesMatrix:
3377 assert(builder.isVector(left));
3378 assert(builder.isMatrix(right));
3379 break;
3380 case spv::OpMatrixTimesVector:
3381 assert(builder.isMatrix(left));
3382 assert(builder.isVector(right));
3383 break;
3384 case spv::OpMatrixTimesMatrix:
3385 assert(builder.isMatrix(left));
3386 assert(builder.isMatrix(right));
3387 break;
3388 default:
3389 firstClass = false;
3390 break;
3391 }
3392
qining25262b32016-05-06 17:25:16 -04003393 if (firstClass) {
3394 spv::Id result = builder.createBinOp(op, typeId, left, right);
3395 addDecoration(result, noContraction);
3396 return builder.setPrecision(result, precision);
3397 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003398
LoopDawg592860c2016-06-09 08:57:35 -06003399 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003400 // The result type of all of them is the same type as the (a) matrix operand.
3401 // The algorithm is to:
3402 // - break the matrix(es) into vectors
3403 // - smear any scalar to a vector
3404 // - do vector operations
3405 // - make a matrix out the vector results
3406 switch (op) {
3407 case spv::OpFAdd:
3408 case spv::OpFSub:
3409 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003410 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003411 case spv::OpFMul:
3412 {
3413 // one time set up...
3414 bool leftMat = builder.isMatrix(left);
3415 bool rightMat = builder.isMatrix(right);
3416 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3417 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3418 spv::Id scalarType = builder.getScalarTypeId(typeId);
3419 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3420 std::vector<spv::Id> results;
3421 spv::Id smearVec = spv::NoResult;
3422 if (builder.isScalar(left))
3423 smearVec = builder.smearScalar(precision, left, vecType);
3424 else if (builder.isScalar(right))
3425 smearVec = builder.smearScalar(precision, right, vecType);
3426
3427 // do each vector op
3428 for (unsigned int c = 0; c < numCols; ++c) {
3429 std::vector<unsigned int> indexes;
3430 indexes.push_back(c);
3431 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3432 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003433 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3434 addDecoration(result, noContraction);
3435 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003436 }
3437
3438 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003439 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003440 }
3441 default:
3442 assert(0);
3443 return spv::NoResult;
3444 }
3445}
3446
qining25262b32016-05-06 17:25:16 -04003447spv::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 -06003448{
3449 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003450 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003451 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003452 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003453#ifdef AMD_EXTENSIONS
3454 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3455#else
Rex Xu04db3f52015-09-16 11:44:02 +08003456 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003457#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003458
3459 switch (op) {
3460 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003461 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003462 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003463 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003464 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003465 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003466 unaryOp = spv::OpSNegate;
3467 break;
3468
3469 case glslang::EOpLogicalNot:
3470 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003471 unaryOp = spv::OpLogicalNot;
3472 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 case glslang::EOpBitwiseNot:
3474 unaryOp = spv::OpNot;
3475 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003476
John Kessenich140f3df2015-06-26 16:58:36 -06003477 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003481 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483 case glslang::EOpTranspose:
3484 unaryOp = spv::OpTranspose;
3485 break;
3486
3487 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003504 break;
3505 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003506 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003507 break;
3508 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003509 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003510 break;
3511
3512 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003513 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 break;
3515 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 break;
3524 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
3527 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003528 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003529 break;
3530
3531 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003532 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003533 break;
3534 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003535 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003536 break;
3537
3538 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003539 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003540 break;
3541 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003542 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003543 break;
3544 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003545 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
3547 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003548 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003549 break;
3550 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003554 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556
3557 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003558 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003559 break;
3560 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003561 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003562 break;
3563 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003564 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003565 break;
3566 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003567 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003568 break;
3569 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003570 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003571 break;
3572 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003573 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003574 break;
3575
3576 case glslang::EOpIsNan:
3577 unaryOp = spv::OpIsNan;
3578 break;
3579 case glslang::EOpIsInf:
3580 unaryOp = spv::OpIsInf;
3581 break;
LoopDawg592860c2016-06-09 08:57:35 -06003582 case glslang::EOpIsFinite:
3583 unaryOp = spv::OpIsFinite;
3584 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003585
Rex Xucbc426e2015-12-15 16:03:10 +08003586 case glslang::EOpFloatBitsToInt:
3587 case glslang::EOpFloatBitsToUint:
3588 case glslang::EOpIntBitsToFloat:
3589 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003590 case glslang::EOpDoubleBitsToInt64:
3591 case glslang::EOpDoubleBitsToUint64:
3592 case glslang::EOpInt64BitsToDouble:
3593 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003594 unaryOp = spv::OpBitcast;
3595 break;
3596
John Kessenich140f3df2015-06-26 16:58:36 -06003597 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003598 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003599 break;
3600 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003601 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 break;
3606 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003607 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003608 break;
3609 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003610 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 break;
3612 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003613 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003615 case glslang::EOpPackSnorm4x8:
3616 libCall = spv::GLSLstd450PackSnorm4x8;
3617 break;
3618 case glslang::EOpUnpackSnorm4x8:
3619 libCall = spv::GLSLstd450UnpackSnorm4x8;
3620 break;
3621 case glslang::EOpPackUnorm4x8:
3622 libCall = spv::GLSLstd450PackUnorm4x8;
3623 break;
3624 case glslang::EOpUnpackUnorm4x8:
3625 libCall = spv::GLSLstd450UnpackUnorm4x8;
3626 break;
3627 case glslang::EOpPackDouble2x32:
3628 libCall = spv::GLSLstd450PackDouble2x32;
3629 break;
3630 case glslang::EOpUnpackDouble2x32:
3631 libCall = spv::GLSLstd450UnpackDouble2x32;
3632 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003633
Rex Xu8ff43de2016-04-22 16:51:45 +08003634 case glslang::EOpPackInt2x32:
3635 case glslang::EOpUnpackInt2x32:
3636 case glslang::EOpPackUint2x32:
3637 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003638 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003639 break;
3640
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003641#ifdef AMD_EXTENSIONS
3642 case glslang::EOpPackFloat2x16:
3643 case glslang::EOpUnpackFloat2x16:
3644 unaryOp = spv::OpBitcast;
3645 break;
3646#endif
3647
John Kessenich140f3df2015-06-26 16:58:36 -06003648 case glslang::EOpDPdx:
3649 unaryOp = spv::OpDPdx;
3650 break;
3651 case glslang::EOpDPdy:
3652 unaryOp = spv::OpDPdy;
3653 break;
3654 case glslang::EOpFwidth:
3655 unaryOp = spv::OpFwidth;
3656 break;
3657 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003658 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003659 unaryOp = spv::OpDPdxFine;
3660 break;
3661 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003662 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003663 unaryOp = spv::OpDPdyFine;
3664 break;
3665 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003666 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003667 unaryOp = spv::OpFwidthFine;
3668 break;
3669 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003670 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003671 unaryOp = spv::OpDPdxCoarse;
3672 break;
3673 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003674 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003675 unaryOp = spv::OpDPdyCoarse;
3676 break;
3677 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003678 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003679 unaryOp = spv::OpFwidthCoarse;
3680 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003681 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003682 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003683 libCall = spv::GLSLstd450InterpolateAtCentroid;
3684 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003685 case glslang::EOpAny:
3686 unaryOp = spv::OpAny;
3687 break;
3688 case glslang::EOpAll:
3689 unaryOp = spv::OpAll;
3690 break;
3691
3692 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 if (isFloat)
3694 libCall = spv::GLSLstd450FAbs;
3695 else
3696 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 if (isFloat)
3700 libCall = spv::GLSLstd450FSign;
3701 else
3702 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704
John Kessenichfc51d282015-08-19 13:34:18 -06003705 case glslang::EOpAtomicCounterIncrement:
3706 case glslang::EOpAtomicCounterDecrement:
3707 case glslang::EOpAtomicCounter:
3708 {
3709 // Handle all of the atomics in one place, in createAtomicOperation()
3710 std::vector<spv::Id> operands;
3711 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003712 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003713 }
3714
John Kessenichfc51d282015-08-19 13:34:18 -06003715 case glslang::EOpBitFieldReverse:
3716 unaryOp = spv::OpBitReverse;
3717 break;
3718 case glslang::EOpBitCount:
3719 unaryOp = spv::OpBitCount;
3720 break;
3721 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003722 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003723 break;
3724 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003725 if (isUnsigned)
3726 libCall = spv::GLSLstd450FindUMsb;
3727 else
3728 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003729 break;
3730
Rex Xu574ab042016-04-14 16:53:07 +08003731 case glslang::EOpBallot:
3732 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003733 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003734 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003735 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003736#ifdef AMD_EXTENSIONS
3737 case glslang::EOpMinInvocations:
3738 case glslang::EOpMaxInvocations:
3739 case glslang::EOpAddInvocations:
3740 case glslang::EOpMinInvocationsNonUniform:
3741 case glslang::EOpMaxInvocationsNonUniform:
3742 case glslang::EOpAddInvocationsNonUniform:
3743#endif
Rex Xu51596642016-09-21 18:56:12 +08003744 {
3745 std::vector<spv::Id> operands;
3746 operands.push_back(operand);
3747 return createInvocationsOperation(op, typeId, operands, typeProxy);
3748 }
Rex Xu9d93a232016-05-05 12:30:44 +08003749
3750#ifdef AMD_EXTENSIONS
3751 case glslang::EOpMbcnt:
3752 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3753 libCall = spv::MbcntAMD;
3754 break;
3755
3756 case glslang::EOpCubeFaceIndex:
3757 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3758 libCall = spv::CubeFaceIndexAMD;
3759 break;
3760
3761 case glslang::EOpCubeFaceCoord:
3762 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3763 libCall = spv::CubeFaceCoordAMD;
3764 break;
3765#endif
Rex Xu338b1852016-05-05 20:38:33 +08003766
John Kessenich140f3df2015-06-26 16:58:36 -06003767 default:
3768 return 0;
3769 }
3770
3771 spv::Id id;
3772 if (libCall >= 0) {
3773 std::vector<spv::Id> args;
3774 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003775 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003776 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003777 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003778 }
John Kessenich140f3df2015-06-26 16:58:36 -06003779
qining25262b32016-05-06 17:25:16 -04003780 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003781 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003782}
3783
John Kessenich7a53f762016-01-20 11:19:27 -07003784// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003785spv::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 -07003786{
3787 // Handle unary operations vector by vector.
3788 // The result type is the same type as the original type.
3789 // The algorithm is to:
3790 // - break the matrix into vectors
3791 // - apply the operation to each vector
3792 // - make a matrix out the vector results
3793
3794 // get the types sorted out
3795 int numCols = builder.getNumColumns(operand);
3796 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003797 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3798 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003799 std::vector<spv::Id> results;
3800
3801 // do each vector op
3802 for (int c = 0; c < numCols; ++c) {
3803 std::vector<unsigned int> indexes;
3804 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003805 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3806 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3807 addDecoration(destVec, noContraction);
3808 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003809 }
3810
3811 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003812 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003813}
3814
Rex Xu73e3ce72016-04-27 18:48:17 +08003815spv::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 -06003816{
3817 spv::Op convOp = spv::OpNop;
3818 spv::Id zero = 0;
3819 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003820 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003821
3822 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3823
3824 switch (op) {
3825 case glslang::EOpConvIntToBool:
3826 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003827 case glslang::EOpConvInt64ToBool:
3828 case glslang::EOpConvUint64ToBool:
3829 zero = (op == glslang::EOpConvInt64ToBool ||
3830 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003831 zero = makeSmearedConstant(zero, vectorSize);
3832 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3833
3834 case glslang::EOpConvFloatToBool:
3835 zero = builder.makeFloatConstant(0.0F);
3836 zero = makeSmearedConstant(zero, vectorSize);
3837 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3838
3839 case glslang::EOpConvDoubleToBool:
3840 zero = builder.makeDoubleConstant(0.0);
3841 zero = makeSmearedConstant(zero, vectorSize);
3842 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3843
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003844#ifdef AMD_EXTENSIONS
3845 case glslang::EOpConvFloat16ToBool:
3846 zero = builder.makeFloat16Constant(0.0F);
3847 zero = makeSmearedConstant(zero, vectorSize);
3848 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3849#endif
3850
John Kessenich140f3df2015-06-26 16:58:36 -06003851 case glslang::EOpConvBoolToFloat:
3852 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003853 zero = builder.makeFloatConstant(0.0F);
3854 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003856
John Kessenich140f3df2015-06-26 16:58:36 -06003857 case glslang::EOpConvBoolToDouble:
3858 convOp = spv::OpSelect;
3859 zero = builder.makeDoubleConstant(0.0);
3860 one = builder.makeDoubleConstant(1.0);
3861 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003862
3863#ifdef AMD_EXTENSIONS
3864 case glslang::EOpConvBoolToFloat16:
3865 convOp = spv::OpSelect;
3866 zero = builder.makeFloat16Constant(0.0F);
3867 one = builder.makeFloat16Constant(1.0F);
3868 break;
3869#endif
3870
John Kessenich140f3df2015-06-26 16:58:36 -06003871 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003872 case glslang::EOpConvBoolToInt64:
3873 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3874 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003875 convOp = spv::OpSelect;
3876 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003877
John Kessenich140f3df2015-06-26 16:58:36 -06003878 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003879 case glslang::EOpConvBoolToUint64:
3880 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3881 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003882 convOp = spv::OpSelect;
3883 break;
3884
3885 case glslang::EOpConvIntToFloat:
3886 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003887 case glslang::EOpConvInt64ToFloat:
3888 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003889#ifdef AMD_EXTENSIONS
3890 case glslang::EOpConvIntToFloat16:
3891 case glslang::EOpConvInt64ToFloat16:
3892#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003893 convOp = spv::OpConvertSToF;
3894 break;
3895
3896 case glslang::EOpConvUintToFloat:
3897 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003898 case glslang::EOpConvUint64ToFloat:
3899 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003900#ifdef AMD_EXTENSIONS
3901 case glslang::EOpConvUintToFloat16:
3902 case glslang::EOpConvUint64ToFloat16:
3903#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003904 convOp = spv::OpConvertUToF;
3905 break;
3906
3907 case glslang::EOpConvDoubleToFloat:
3908 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003909#ifdef AMD_EXTENSIONS
3910 case glslang::EOpConvDoubleToFloat16:
3911 case glslang::EOpConvFloat16ToDouble:
3912 case glslang::EOpConvFloatToFloat16:
3913 case glslang::EOpConvFloat16ToFloat:
3914#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003915 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003916 if (builder.isMatrixType(destType))
3917 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003918 break;
3919
3920 case glslang::EOpConvFloatToInt:
3921 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003922 case glslang::EOpConvFloatToInt64:
3923 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003924#ifdef AMD_EXTENSIONS
3925 case glslang::EOpConvFloat16ToInt:
3926 case glslang::EOpConvFloat16ToInt64:
3927#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003928 convOp = spv::OpConvertFToS;
3929 break;
3930
3931 case glslang::EOpConvUintToInt:
3932 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003933 case glslang::EOpConvUint64ToInt64:
3934 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003935 if (builder.isInSpecConstCodeGenMode()) {
3936 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003937 zero = (op == glslang::EOpConvUint64ToInt64 ||
3938 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003939 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003940 // Use OpIAdd, instead of OpBitcast to do the conversion when
3941 // generating for OpSpecConstantOp instruction.
3942 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3943 }
3944 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003945 convOp = spv::OpBitcast;
3946 break;
3947
3948 case glslang::EOpConvFloatToUint:
3949 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003950 case glslang::EOpConvFloatToUint64:
3951 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003952#ifdef AMD_EXTENSIONS
3953 case glslang::EOpConvFloat16ToUint:
3954 case glslang::EOpConvFloat16ToUint64:
3955#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003956 convOp = spv::OpConvertFToU;
3957 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003958
3959 case glslang::EOpConvIntToInt64:
3960 case glslang::EOpConvInt64ToInt:
3961 convOp = spv::OpSConvert;
3962 break;
3963
3964 case glslang::EOpConvUintToUint64:
3965 case glslang::EOpConvUint64ToUint:
3966 convOp = spv::OpUConvert;
3967 break;
3968
3969 case glslang::EOpConvIntToUint64:
3970 case glslang::EOpConvInt64ToUint:
3971 case glslang::EOpConvUint64ToInt:
3972 case glslang::EOpConvUintToInt64:
3973 // OpSConvert/OpUConvert + OpBitCast
3974 switch (op) {
3975 case glslang::EOpConvIntToUint64:
3976 convOp = spv::OpSConvert;
3977 type = builder.makeIntType(64);
3978 break;
3979 case glslang::EOpConvInt64ToUint:
3980 convOp = spv::OpSConvert;
3981 type = builder.makeIntType(32);
3982 break;
3983 case glslang::EOpConvUint64ToInt:
3984 convOp = spv::OpUConvert;
3985 type = builder.makeUintType(32);
3986 break;
3987 case glslang::EOpConvUintToInt64:
3988 convOp = spv::OpUConvert;
3989 type = builder.makeUintType(64);
3990 break;
3991 default:
3992 assert(0);
3993 break;
3994 }
3995
3996 if (vectorSize > 0)
3997 type = builder.makeVectorType(type, vectorSize);
3998
3999 operand = builder.createUnaryOp(convOp, type, operand);
4000
4001 if (builder.isInSpecConstCodeGenMode()) {
4002 // Build zero scalar or vector for OpIAdd.
4003 zero = (op == glslang::EOpConvIntToUint64 ||
4004 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4005 zero = makeSmearedConstant(zero, vectorSize);
4006 // Use OpIAdd, instead of OpBitcast to do the conversion when
4007 // generating for OpSpecConstantOp instruction.
4008 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4009 }
4010 // For normal run-time conversion instruction, use OpBitcast.
4011 convOp = spv::OpBitcast;
4012 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004013 default:
4014 break;
4015 }
4016
4017 spv::Id result = 0;
4018 if (convOp == spv::OpNop)
4019 return result;
4020
4021 if (convOp == spv::OpSelect) {
4022 zero = makeSmearedConstant(zero, vectorSize);
4023 one = makeSmearedConstant(one, vectorSize);
4024 result = builder.createTriOp(convOp, destType, operand, one, zero);
4025 } else
4026 result = builder.createUnaryOp(convOp, destType, operand);
4027
John Kessenich32cfd492016-02-02 12:37:46 -07004028 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004029}
4030
4031spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4032{
4033 if (vectorSize == 0)
4034 return constant;
4035
4036 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4037 std::vector<spv::Id> components;
4038 for (int c = 0; c < vectorSize; ++c)
4039 components.push_back(constant);
4040 return builder.makeCompositeConstant(vectorTypeId, components);
4041}
4042
John Kessenich426394d2015-07-23 10:22:48 -06004043// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004044spv::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 -06004045{
4046 spv::Op opCode = spv::OpNop;
4047
4048 switch (op) {
4049 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004050 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004051 opCode = spv::OpAtomicIAdd;
4052 break;
4053 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004054 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004055 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004056 break;
4057 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004058 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004059 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004060 break;
4061 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004062 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004063 opCode = spv::OpAtomicAnd;
4064 break;
4065 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004066 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004067 opCode = spv::OpAtomicOr;
4068 break;
4069 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004070 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004071 opCode = spv::OpAtomicXor;
4072 break;
4073 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004074 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004075 opCode = spv::OpAtomicExchange;
4076 break;
4077 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004078 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004079 opCode = spv::OpAtomicCompareExchange;
4080 break;
4081 case glslang::EOpAtomicCounterIncrement:
4082 opCode = spv::OpAtomicIIncrement;
4083 break;
4084 case glslang::EOpAtomicCounterDecrement:
4085 opCode = spv::OpAtomicIDecrement;
4086 break;
4087 case glslang::EOpAtomicCounter:
4088 opCode = spv::OpAtomicLoad;
4089 break;
4090 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004091 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004092 break;
4093 }
4094
4095 // Sort out the operands
4096 // - mapping from glslang -> SPV
4097 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004098 // - compare-exchange swaps the value and comparator
4099 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004100 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4101 auto opIt = operands.begin(); // walk the glslang operands
4102 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004103 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4104 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4105 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004106 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4107 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004108 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004109 spvAtomicOperands.push_back(*(opIt + 1));
4110 spvAtomicOperands.push_back(*opIt);
4111 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004112 }
John Kessenich426394d2015-07-23 10:22:48 -06004113
John Kessenich3e60a6f2015-09-14 22:45:16 -06004114 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004115 for (; opIt != operands.end(); ++opIt)
4116 spvAtomicOperands.push_back(*opIt);
4117
4118 return builder.createOp(opCode, typeId, spvAtomicOperands);
4119}
4120
John Kessenich91cef522016-05-05 16:45:40 -06004121// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004122spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004123{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004124#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004125 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004126 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004127#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004128
Rex Xu51596642016-09-21 18:56:12 +08004129 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004130
Rex Xu51596642016-09-21 18:56:12 +08004131 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004132 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4133 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004134 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4135 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4136 } else {
4137 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004138#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004139 if (op == glslang::EOpMinInvocationsNonUniform ||
4140 op == glslang::EOpMaxInvocationsNonUniform ||
4141 op == glslang::EOpAddInvocationsNonUniform)
4142 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004143#endif
Rex Xu51596642016-09-21 18:56:12 +08004144
4145 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004146#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004147 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4148 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4149 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004150#endif
Rex Xu51596642016-09-21 18:56:12 +08004151 }
4152
4153 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4154 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004155
4156 switch (op) {
4157 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004158 opCode = spv::OpGroupAny;
4159 break;
John Kessenich91cef522016-05-05 16:45:40 -06004160 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004161 opCode = spv::OpGroupAll;
4162 break;
John Kessenich91cef522016-05-05 16:45:40 -06004163 case glslang::EOpAllInvocationsEqual:
4164 {
Rex Xu51596642016-09-21 18:56:12 +08004165 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4166 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004167
4168 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4169 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4170 }
Rex Xu51596642016-09-21 18:56:12 +08004171
4172 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004173 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004174 if (builder.isVectorType(typeId))
4175 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004176 break;
4177 case glslang::EOpReadFirstInvocation:
4178 opCode = spv::OpSubgroupFirstInvocationKHR;
4179 break;
4180 case glslang::EOpBallot:
4181 {
4182 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4183 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4184 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4185 //
4186 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4187 //
4188 spv::Id uintType = builder.makeUintType(32);
4189 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4190 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4191
4192 std::vector<spv::Id> components;
4193 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4194 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4195
4196 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4197 return builder.createUnaryOp(spv::OpBitcast, typeId,
4198 builder.createCompositeConstruct(uvec2Type, components));
4199 }
4200
Rex Xu9d93a232016-05-05 12:30:44 +08004201#ifdef AMD_EXTENSIONS
4202 case glslang::EOpMinInvocations:
4203 case glslang::EOpMaxInvocations:
4204 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004205 if (op == glslang::EOpMinInvocations) {
4206 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004207 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004208 else {
4209 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004210 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004211 else
Rex Xu51596642016-09-21 18:56:12 +08004212 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004213 }
4214 } else if (op == glslang::EOpMaxInvocations) {
4215 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004216 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004217 else {
4218 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004219 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004220 else
Rex Xu51596642016-09-21 18:56:12 +08004221 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004222 }
4223 } else {
4224 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004225 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004226 else
Rex Xu51596642016-09-21 18:56:12 +08004227 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004228 }
4229
Rex Xu2bbbe062016-08-23 15:41:05 +08004230 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004231 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004232
4233 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004234 case glslang::EOpMinInvocationsNonUniform:
4235 case glslang::EOpMaxInvocationsNonUniform:
4236 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004237 if (op == glslang::EOpMinInvocationsNonUniform) {
4238 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004239 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004240 else {
4241 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004242 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004243 else
Rex Xu51596642016-09-21 18:56:12 +08004244 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004245 }
4246 }
4247 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4248 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004249 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004250 else {
4251 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004252 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004253 else
Rex Xu51596642016-09-21 18:56:12 +08004254 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004255 }
4256 }
4257 else {
4258 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004259 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004260 else
Rex Xu51596642016-09-21 18:56:12 +08004261 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004262 }
4263
Rex Xu2bbbe062016-08-23 15:41:05 +08004264 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004265 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004266
4267 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004268#endif
John Kessenich91cef522016-05-05 16:45:40 -06004269 default:
4270 logger->missingFunctionality("invocation operation");
4271 return spv::NoResult;
4272 }
Rex Xu51596642016-09-21 18:56:12 +08004273
4274 assert(opCode != spv::OpNop);
4275 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004276}
4277
Rex Xu2bbbe062016-08-23 15:41:05 +08004278// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004279spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004280{
Rex Xub7072052016-09-26 15:53:40 +08004281#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004282 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4283 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004284 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004285 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004286 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4287 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4288 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004289#else
4290 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4291 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004292 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4293 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004294#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004295
4296 // Handle group invocation operations scalar by scalar.
4297 // The result type is the same type as the original type.
4298 // The algorithm is to:
4299 // - break the vector into scalars
4300 // - apply the operation to each scalar
4301 // - make a vector out the scalar results
4302
4303 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004304 int numComponents = builder.getNumComponents(operands[0]);
4305 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004306 std::vector<spv::Id> results;
4307
4308 // do each scalar op
4309 for (int comp = 0; comp < numComponents; ++comp) {
4310 std::vector<unsigned int> indexes;
4311 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004312 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004313 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004314 if (op == spv::OpSubgroupReadInvocationKHR) {
4315 spvGroupOperands.push_back(scalar);
4316 spvGroupOperands.push_back(operands[1]);
4317 } else if (op == spv::OpGroupBroadcast) {
4318 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004319 spvGroupOperands.push_back(scalar);
4320 spvGroupOperands.push_back(operands[1]);
4321 } else {
chaocf200da82016-12-20 12:44:35 -08004322 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004323 spvGroupOperands.push_back(spv::GroupOperationReduce);
4324 spvGroupOperands.push_back(scalar);
4325 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004326
Rex Xub7072052016-09-26 15:53:40 +08004327 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004328 }
4329
4330 // put the pieces together
4331 return builder.createCompositeConstruct(typeId, results);
4332}
Rex Xu2bbbe062016-08-23 15:41:05 +08004333
John Kessenich5e4b1242015-08-06 22:53:06 -06004334spv::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 -06004335{
Rex Xu8ff43de2016-04-22 16:51:45 +08004336 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004337#ifdef AMD_EXTENSIONS
4338 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4339#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004340 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004341#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004342
John Kessenich140f3df2015-06-26 16:58:36 -06004343 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004344 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004345 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004346 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004347 spv::Id typeId0 = 0;
4348 if (consumedOperands > 0)
4349 typeId0 = builder.getTypeId(operands[0]);
4350 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004351
4352 switch (op) {
4353 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004354 if (isFloat)
4355 libCall = spv::GLSLstd450FMin;
4356 else if (isUnsigned)
4357 libCall = spv::GLSLstd450UMin;
4358 else
4359 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004360 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004361 break;
4362 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004363 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004364 break;
4365 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 if (isFloat)
4367 libCall = spv::GLSLstd450FMax;
4368 else if (isUnsigned)
4369 libCall = spv::GLSLstd450UMax;
4370 else
4371 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004372 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004373 break;
4374 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004375 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004376 break;
4377 case glslang::EOpDot:
4378 opCode = spv::OpDot;
4379 break;
4380 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004381 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004382 break;
4383
4384 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004385 if (isFloat)
4386 libCall = spv::GLSLstd450FClamp;
4387 else if (isUnsigned)
4388 libCall = spv::GLSLstd450UClamp;
4389 else
4390 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004391 builder.promoteScalar(precision, operands.front(), operands[1]);
4392 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004393 break;
4394 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004395 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4396 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004397 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004398 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004399 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004400 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004401 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004402 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004403 break;
4404 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004405 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004406 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004407 break;
4408 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004409 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004410 builder.promoteScalar(precision, operands[0], operands[2]);
4411 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004412 break;
4413
4414 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004415 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004416 break;
4417 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004418 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004419 break;
4420 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004422 break;
4423 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004424 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004425 break;
4426 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004427 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004428 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004429 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004430 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004431 libCall = spv::GLSLstd450InterpolateAtSample;
4432 break;
4433 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004434 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004435 libCall = spv::GLSLstd450InterpolateAtOffset;
4436 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004437 case glslang::EOpAddCarry:
4438 opCode = spv::OpIAddCarry;
4439 typeId = builder.makeStructResultType(typeId0, typeId0);
4440 consumedOperands = 2;
4441 break;
4442 case glslang::EOpSubBorrow:
4443 opCode = spv::OpISubBorrow;
4444 typeId = builder.makeStructResultType(typeId0, typeId0);
4445 consumedOperands = 2;
4446 break;
4447 case glslang::EOpUMulExtended:
4448 opCode = spv::OpUMulExtended;
4449 typeId = builder.makeStructResultType(typeId0, typeId0);
4450 consumedOperands = 2;
4451 break;
4452 case glslang::EOpIMulExtended:
4453 opCode = spv::OpSMulExtended;
4454 typeId = builder.makeStructResultType(typeId0, typeId0);
4455 consumedOperands = 2;
4456 break;
4457 case glslang::EOpBitfieldExtract:
4458 if (isUnsigned)
4459 opCode = spv::OpBitFieldUExtract;
4460 else
4461 opCode = spv::OpBitFieldSExtract;
4462 break;
4463 case glslang::EOpBitfieldInsert:
4464 opCode = spv::OpBitFieldInsert;
4465 break;
4466
4467 case glslang::EOpFma:
4468 libCall = spv::GLSLstd450Fma;
4469 break;
4470 case glslang::EOpFrexp:
4471 libCall = spv::GLSLstd450FrexpStruct;
4472 if (builder.getNumComponents(operands[0]) == 1)
4473 frexpIntType = builder.makeIntegerType(32, true);
4474 else
4475 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4476 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4477 consumedOperands = 1;
4478 break;
4479 case glslang::EOpLdexp:
4480 libCall = spv::GLSLstd450Ldexp;
4481 break;
4482
Rex Xu574ab042016-04-14 16:53:07 +08004483 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004484 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004485
Rex Xu9d93a232016-05-05 12:30:44 +08004486#ifdef AMD_EXTENSIONS
4487 case glslang::EOpSwizzleInvocations:
4488 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4489 libCall = spv::SwizzleInvocationsAMD;
4490 break;
4491 case glslang::EOpSwizzleInvocationsMasked:
4492 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4493 libCall = spv::SwizzleInvocationsMaskedAMD;
4494 break;
4495 case glslang::EOpWriteInvocation:
4496 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4497 libCall = spv::WriteInvocationAMD;
4498 break;
4499
4500 case glslang::EOpMin3:
4501 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4502 if (isFloat)
4503 libCall = spv::FMin3AMD;
4504 else {
4505 if (isUnsigned)
4506 libCall = spv::UMin3AMD;
4507 else
4508 libCall = spv::SMin3AMD;
4509 }
4510 break;
4511 case glslang::EOpMax3:
4512 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4513 if (isFloat)
4514 libCall = spv::FMax3AMD;
4515 else {
4516 if (isUnsigned)
4517 libCall = spv::UMax3AMD;
4518 else
4519 libCall = spv::SMax3AMD;
4520 }
4521 break;
4522 case glslang::EOpMid3:
4523 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4524 if (isFloat)
4525 libCall = spv::FMid3AMD;
4526 else {
4527 if (isUnsigned)
4528 libCall = spv::UMid3AMD;
4529 else
4530 libCall = spv::SMid3AMD;
4531 }
4532 break;
4533
4534 case glslang::EOpInterpolateAtVertex:
4535 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4536 libCall = spv::InterpolateAtVertexAMD;
4537 break;
4538#endif
4539
John Kessenich140f3df2015-06-26 16:58:36 -06004540 default:
4541 return 0;
4542 }
4543
4544 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004545 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004546 // Use an extended instruction from the standard library.
4547 // Construct the call arguments, without modifying the original operands vector.
4548 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4549 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004550 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004551 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004552 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004553 case 0:
4554 // should all be handled by visitAggregate and createNoArgOperation
4555 assert(0);
4556 return 0;
4557 case 1:
4558 // should all be handled by createUnaryOperation
4559 assert(0);
4560 return 0;
4561 case 2:
4562 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4563 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004564 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004565 // anything 3 or over doesn't have l-value operands, so all should be consumed
4566 assert(consumedOperands == operands.size());
4567 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004568 break;
4569 }
4570 }
4571
John Kessenich55e7d112015-11-15 21:33:39 -07004572 // Decode the return types that were structures
4573 switch (op) {
4574 case glslang::EOpAddCarry:
4575 case glslang::EOpSubBorrow:
4576 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4577 id = builder.createCompositeExtract(id, typeId0, 0);
4578 break;
4579 case glslang::EOpUMulExtended:
4580 case glslang::EOpIMulExtended:
4581 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4582 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4583 break;
4584 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004585 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004586 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4587 id = builder.createCompositeExtract(id, typeId0, 0);
4588 break;
4589 default:
4590 break;
4591 }
4592
John Kessenich32cfd492016-02-02 12:37:46 -07004593 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004594}
4595
Rex Xu9d93a232016-05-05 12:30:44 +08004596// Intrinsics with no arguments (or no return value, and no precision).
4597spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004598{
4599 // TODO: get the barrier operands correct
4600
4601 switch (op) {
4602 case glslang::EOpEmitVertex:
4603 builder.createNoResultOp(spv::OpEmitVertex);
4604 return 0;
4605 case glslang::EOpEndPrimitive:
4606 builder.createNoResultOp(spv::OpEndPrimitive);
4607 return 0;
4608 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004609 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004610 return 0;
4611 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004612 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 return 0;
4614 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004616 return 0;
4617 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004618 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004619 return 0;
4620 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004621 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004622 return 0;
4623 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004624 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004625 return 0;
4626 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004627 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004628 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004629 case glslang::EOpAllMemoryBarrierWithGroupSync:
4630 // Control barrier with non-"None" semantic is also a memory barrier.
4631 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4632 return 0;
4633 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4634 // Control barrier with non-"None" semantic is also a memory barrier.
4635 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4636 return 0;
4637 case glslang::EOpWorkgroupMemoryBarrier:
4638 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4639 return 0;
4640 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4641 // Control barrier with non-"None" semantic is also a memory barrier.
4642 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4643 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004644#ifdef AMD_EXTENSIONS
4645 case glslang::EOpTime:
4646 {
4647 std::vector<spv::Id> args; // Dummy arguments
4648 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4649 return builder.setPrecision(id, precision);
4650 }
4651#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004652 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004653 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004654 return 0;
4655 }
4656}
4657
4658spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4659{
John Kessenich2f273362015-07-18 22:34:27 -06004660 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004661 spv::Id id;
4662 if (symbolValues.end() != iter) {
4663 id = iter->second;
4664 return id;
4665 }
4666
4667 // it was not found, create it
4668 id = createSpvVariable(symbol);
4669 symbolValues[symbol->getId()] = id;
4670
Rex Xuc884b4a2016-06-29 15:03:44 +08004671 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004672 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004673 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004674 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004675 if (symbol->getType().getQualifier().hasSpecConstantId())
4676 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004677 if (symbol->getQualifier().hasIndex())
4678 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4679 if (symbol->getQualifier().hasComponent())
4680 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4681 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004682 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004683 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004684 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004685 if (symbol->getQualifier().hasXfbBuffer())
4686 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4687 if (symbol->getQualifier().hasXfbOffset())
4688 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4689 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004690 // atomic counters use this:
4691 if (symbol->getQualifier().hasOffset())
4692 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004693 }
4694
scygan2c864272016-05-18 18:09:17 +02004695 if (symbol->getQualifier().hasLocation())
4696 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004697 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004698 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004699 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004700 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004701 }
John Kessenich140f3df2015-06-26 16:58:36 -06004702 if (symbol->getQualifier().hasSet())
4703 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004704 else if (IsDescriptorResource(symbol->getType())) {
4705 // default to 0
4706 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4707 }
John Kessenich140f3df2015-06-26 16:58:36 -06004708 if (symbol->getQualifier().hasBinding())
4709 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004710 if (symbol->getQualifier().hasAttachment())
4711 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004712 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004713 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004714 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004715 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004716 if (symbol->getQualifier().hasXfbBuffer())
4717 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4718 }
4719
Rex Xu1da878f2016-02-21 20:59:01 +08004720 if (symbol->getType().isImage()) {
4721 std::vector<spv::Decoration> memory;
4722 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4723 for (unsigned int i = 0; i < memory.size(); ++i)
4724 addDecoration(id, memory[i]);
4725 }
4726
John Kessenich140f3df2015-06-26 16:58:36 -06004727 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004728 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004729 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004730 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004731
John Kessenichecba76f2017-01-06 00:34:48 -07004732#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004733 if (builtIn == spv::BuiltInSampleMask) {
4734 spv::Decoration decoration;
4735 // GL_NV_sample_mask_override_coverage extension
4736 if (glslangIntermediate->getLayoutOverrideCoverage())
4737 decoration = (spv::Decoration)spv::OverrideCoverageNV;
4738 else
4739 decoration = (spv::Decoration)spv::DecorationMax;
4740 addDecoration(id, decoration);
4741 if (decoration != spv::DecorationMax) {
4742 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4743 }
4744 }
chaoc6e5acae2016-12-20 13:28:52 -08004745 if (symbol->getQualifier().layoutPassthrough) {
4746 addDecoration(id, spv::PassthroughNV);
4747 builder.addCapability(spv::GeometryShaderPassthroughNV);
4748 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4749 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004750#endif
4751
John Kessenich140f3df2015-06-26 16:58:36 -06004752 return id;
4753}
4754
John Kessenich55e7d112015-11-15 21:33:39 -07004755// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004756void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4757{
John Kessenich4016e382016-07-15 11:53:56 -06004758 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004759 builder.addDecoration(id, dec);
4760}
4761
John Kessenich55e7d112015-11-15 21:33:39 -07004762// If 'dec' is valid, add a one-operand decoration to an object
4763void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4764{
John Kessenich4016e382016-07-15 11:53:56 -06004765 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004766 builder.addDecoration(id, dec, value);
4767}
4768
4769// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004770void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4771{
John Kessenich4016e382016-07-15 11:53:56 -06004772 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004773 builder.addMemberDecoration(id, (unsigned)member, dec);
4774}
4775
John Kessenich92187592016-02-01 13:45:25 -07004776// If 'dec' is valid, add a one-operand decoration to a struct member
4777void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4778{
John Kessenich4016e382016-07-15 11:53:56 -06004779 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004780 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4781}
4782
John Kessenich55e7d112015-11-15 21:33:39 -07004783// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004784// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004785//
4786// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4787//
4788// Recursively walk the nodes. The nodes form a tree whose leaves are
4789// regular constants, which themselves are trees that createSpvConstant()
4790// recursively walks. So, this function walks the "top" of the tree:
4791// - emit specialization constant-building instructions for specConstant
4792// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004793spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004794{
John Kessenich7cc0e282016-03-20 00:46:02 -06004795 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004796
qining4f4bb812016-04-03 23:55:17 -04004797 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004798 if (! node.getQualifier().specConstant) {
4799 // hand off to the non-spec-constant path
4800 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4801 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004802 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004803 nextConst, false);
4804 }
4805
4806 // We now know we have a specialization constant to build
4807
John Kessenichd94c0032016-05-30 19:29:40 -06004808 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004809 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4810 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4811 std::vector<spv::Id> dimConstId;
4812 for (int dim = 0; dim < 3; ++dim) {
4813 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4814 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4815 if (specConst)
4816 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4817 }
4818 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4819 }
4820
4821 // An AST node labelled as specialization constant should be a symbol node.
4822 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4823 if (auto* sn = node.getAsSymbolNode()) {
4824 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004825 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4826 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4827 // will set the builder into spec constant op instruction generating mode.
4828 sub_tree->traverse(this);
4829 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004830 } else if (auto* const_union_array = &sn->getConstArray()){
4831 int nextConst = 0;
4832 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004833 }
4834 }
qining4f4bb812016-04-03 23:55:17 -04004835
4836 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4837 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004838 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004839 exit(1);
4840 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004841}
4842
John Kessenich140f3df2015-06-26 16:58:36 -06004843// Use 'consts' as the flattened glslang source of scalar constants to recursively
4844// build the aggregate SPIR-V constant.
4845//
4846// If there are not enough elements present in 'consts', 0 will be substituted;
4847// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4848//
qining08408382016-03-21 09:51:37 -04004849spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004850{
4851 // vector of constants for SPIR-V
4852 std::vector<spv::Id> spvConsts;
4853
4854 // Type is used for struct and array constants
4855 spv::Id typeId = convertGlslangToSpvType(glslangType);
4856
4857 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004858 glslang::TType elementType(glslangType, 0);
4859 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004860 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004861 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004862 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004863 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004864 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004865 } else if (glslangType.getStruct()) {
4866 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4867 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004868 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004869 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004870 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4871 bool zero = nextConst >= consts.size();
4872 switch (glslangType.getBasicType()) {
4873 case glslang::EbtInt:
4874 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4875 break;
4876 case glslang::EbtUint:
4877 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4878 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004879 case glslang::EbtInt64:
4880 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4881 break;
4882 case glslang::EbtUint64:
4883 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4884 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004885 case glslang::EbtFloat:
4886 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4887 break;
4888 case glslang::EbtDouble:
4889 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4890 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004891#ifdef AMD_EXTENSIONS
4892 case glslang::EbtFloat16:
4893 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4894 break;
4895#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004896 case glslang::EbtBool:
4897 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4898 break;
4899 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004900 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004901 break;
4902 }
4903 ++nextConst;
4904 }
4905 } else {
4906 // we have a non-aggregate (scalar) constant
4907 bool zero = nextConst >= consts.size();
4908 spv::Id scalar = 0;
4909 switch (glslangType.getBasicType()) {
4910 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004911 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004912 break;
4913 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004914 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004915 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004916 case glslang::EbtInt64:
4917 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4918 break;
4919 case glslang::EbtUint64:
4920 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4921 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004922 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004923 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004924 break;
4925 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004926 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004927 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004928#ifdef AMD_EXTENSIONS
4929 case glslang::EbtFloat16:
4930 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4931 break;
4932#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004933 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004934 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004935 break;
4936 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004937 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004938 break;
4939 }
4940 ++nextConst;
4941 return scalar;
4942 }
4943
4944 return builder.makeCompositeConstant(typeId, spvConsts);
4945}
4946
John Kessenich7c1aa102015-10-15 13:29:11 -06004947// Return true if the node is a constant or symbol whose reading has no
4948// non-trivial observable cost or effect.
4949bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4950{
4951 // don't know what this is
4952 if (node == nullptr)
4953 return false;
4954
4955 // a constant is safe
4956 if (node->getAsConstantUnion() != nullptr)
4957 return true;
4958
4959 // not a symbol means non-trivial
4960 if (node->getAsSymbolNode() == nullptr)
4961 return false;
4962
4963 // a symbol, depends on what's being read
4964 switch (node->getType().getQualifier().storage) {
4965 case glslang::EvqTemporary:
4966 case glslang::EvqGlobal:
4967 case glslang::EvqIn:
4968 case glslang::EvqInOut:
4969 case glslang::EvqConst:
4970 case glslang::EvqConstReadOnly:
4971 case glslang::EvqUniform:
4972 return true;
4973 default:
4974 return false;
4975 }
qining25262b32016-05-06 17:25:16 -04004976}
John Kessenich7c1aa102015-10-15 13:29:11 -06004977
4978// A node is trivial if it is a single operation with no side effects.
4979// Error on the side of saying non-trivial.
4980// Return true if trivial.
4981bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4982{
4983 if (node == nullptr)
4984 return false;
4985
4986 // symbols and constants are trivial
4987 if (isTrivialLeaf(node))
4988 return true;
4989
4990 // otherwise, it needs to be a simple operation or one or two leaf nodes
4991
4992 // not a simple operation
4993 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4994 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4995 if (binaryNode == nullptr && unaryNode == nullptr)
4996 return false;
4997
4998 // not on leaf nodes
4999 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5000 return false;
5001
5002 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5003 return false;
5004 }
5005
5006 switch (node->getAsOperator()->getOp()) {
5007 case glslang::EOpLogicalNot:
5008 case glslang::EOpConvIntToBool:
5009 case glslang::EOpConvUintToBool:
5010 case glslang::EOpConvFloatToBool:
5011 case glslang::EOpConvDoubleToBool:
5012 case glslang::EOpEqual:
5013 case glslang::EOpNotEqual:
5014 case glslang::EOpLessThan:
5015 case glslang::EOpGreaterThan:
5016 case glslang::EOpLessThanEqual:
5017 case glslang::EOpGreaterThanEqual:
5018 case glslang::EOpIndexDirect:
5019 case glslang::EOpIndexDirectStruct:
5020 case glslang::EOpLogicalXor:
5021 case glslang::EOpAny:
5022 case glslang::EOpAll:
5023 return true;
5024 default:
5025 return false;
5026 }
5027}
5028
5029// Emit short-circuiting code, where 'right' is never evaluated unless
5030// the left side is true (for &&) or false (for ||).
5031spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5032{
5033 spv::Id boolTypeId = builder.makeBoolType();
5034
5035 // emit left operand
5036 builder.clearAccessChain();
5037 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005038 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005039
5040 // Operands to accumulate OpPhi operands
5041 std::vector<spv::Id> phiOperands;
5042 // accumulate left operand's phi information
5043 phiOperands.push_back(leftId);
5044 phiOperands.push_back(builder.getBuildPoint()->getId());
5045
5046 // Make the two kinds of operation symmetric with a "!"
5047 // || => emit "if (! left) result = right"
5048 // && => emit "if ( left) result = right"
5049 //
5050 // TODO: this runtime "not" for || could be avoided by adding functionality
5051 // to 'builder' to have an "else" without an "then"
5052 if (op == glslang::EOpLogicalOr)
5053 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5054
5055 // make an "if" based on the left value
5056 spv::Builder::If ifBuilder(leftId, builder);
5057
5058 // emit right operand as the "then" part of the "if"
5059 builder.clearAccessChain();
5060 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005061 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005062
5063 // accumulate left operand's phi information
5064 phiOperands.push_back(rightId);
5065 phiOperands.push_back(builder.getBuildPoint()->getId());
5066
5067 // finish the "if"
5068 ifBuilder.makeEndIf();
5069
5070 // phi together the two results
5071 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5072}
5073
Rex Xu9d93a232016-05-05 12:30:44 +08005074// Return type Id of the imported set of extended instructions corresponds to the name.
5075// Import this set if it has not been imported yet.
5076spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5077{
5078 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5079 return extBuiltinMap[name];
5080 else {
Rex Xu51596642016-09-21 18:56:12 +08005081 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005082 spv::Id extBuiltins = builder.import(name);
5083 extBuiltinMap[name] = extBuiltins;
5084 return extBuiltins;
5085 }
5086}
5087
John Kessenich140f3df2015-06-26 16:58:36 -06005088}; // end anonymous namespace
5089
5090namespace glslang {
5091
John Kessenich68d78fd2015-07-12 19:28:10 -06005092void GetSpirvVersion(std::string& version)
5093{
John Kessenich9e55f632015-07-15 10:03:39 -06005094 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005095 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005096 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005097 version = buf;
5098}
5099
John Kessenich140f3df2015-06-26 16:58:36 -06005100// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005101void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005102{
5103 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005104 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005105 for (int i = 0; i < (int)spirv.size(); ++i) {
5106 unsigned int word = spirv[i];
5107 out.write((const char*)&word, 4);
5108 }
5109 out.close();
5110}
5111
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005112// Write SPIR-V out to a text file with 32-bit hexadecimal words
5113void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5114{
5115 std::ofstream out;
5116 out.open(baseName, std::ios::binary | std::ios::out);
5117 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5118 const int WORDS_PER_LINE = 8;
5119 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5120 out << "\t";
5121 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5122 const unsigned int word = spirv[i + j];
5123 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5124 if (i + j + 1 < (int)spirv.size()) {
5125 out << ",";
5126 }
5127 }
5128 out << std::endl;
5129 }
5130 out.close();
5131}
5132
John Kessenich140f3df2015-06-26 16:58:36 -06005133//
5134// Set up the glslang traversal
5135//
5136void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5137{
Lei Zhang17535f72016-05-04 15:55:59 -04005138 spv::SpvBuildLogger logger;
5139 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005140}
5141
Lei Zhang17535f72016-05-04 15:55:59 -04005142void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005143{
John Kessenich140f3df2015-06-26 16:58:36 -06005144 TIntermNode* root = intermediate.getTreeRoot();
5145
5146 if (root == 0)
5147 return;
5148
5149 glslang::GetThreadPoolAllocator().push();
5150
Lei Zhang17535f72016-05-04 15:55:59 -04005151 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005152 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005153 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005154 it.dumpSpv(spirv);
5155
5156 glslang::GetThreadPoolAllocator().pop();
5157}
5158
5159}; // end namespace glslang