blob: 4b7204d99226faf6f6b448e52fa1182276e07e9e [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
chaoc0ad6a4e2016-12-19 16:29:34 -0800442
David Netoa901ffe2016-06-08 14:11:40 +0100443// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
444// associated capabilities when required. For some built-in variables, a capability
445// is generated only when using the variable in an executable instruction, but not when
446// just declaring a struct member variable with it. This is true for PointSize,
447// ClipDistance, and CullDistance.
448spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600449{
450 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700451 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600452 // Defer adding the capability until the built-in is actually used.
453 if (! memberDeclaration) {
454 switch (glslangIntermediate->getStage()) {
455 case EShLangGeometry:
456 builder.addCapability(spv::CapabilityGeometryPointSize);
457 break;
458 case EShLangTessControl:
459 case EShLangTessEvaluation:
460 builder.addCapability(spv::CapabilityTessellationPointSize);
461 break;
462 default:
463 break;
464 }
John Kessenich92187592016-02-01 13:45:25 -0700465 }
466 return spv::BuiltInPointSize;
467
John Kessenichebb50532016-05-16 19:22:05 -0600468 // These *Distance capabilities logically belong here, but if the member is declared and
469 // then never used, consumers of SPIR-V prefer the capability not be declared.
470 // They are now generated when used, rather than here when declared.
471 // Potentially, the specification should be more clear what the minimum
472 // use needed is to trigger the capability.
473 //
John Kessenich92187592016-02-01 13:45:25 -0700474 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100475 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600476 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700477 return spv::BuiltInClipDistance;
478
479 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100480 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600481 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700482 return spv::BuiltInCullDistance;
483
484 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500485 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700486 return spv::BuiltInViewportIndex;
487
John Kessenich5e801132016-02-15 11:09:46 -0700488 case glslang::EbvSampleId:
489 builder.addCapability(spv::CapabilitySampleRateShading);
490 return spv::BuiltInSampleId;
491
492 case glslang::EbvSamplePosition:
493 builder.addCapability(spv::CapabilitySampleRateShading);
494 return spv::BuiltInSamplePosition;
495
496 case glslang::EbvSampleMask:
497 builder.addCapability(spv::CapabilitySampleRateShading);
498 return spv::BuiltInSampleMask;
499
John Kessenich78a45572016-07-08 14:05:15 -0600500 case glslang::EbvLayer:
501 builder.addCapability(spv::CapabilityGeometry);
502 return spv::BuiltInLayer;
503
John Kessenich140f3df2015-06-26 16:58:36 -0600504 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600505 case glslang::EbvVertexId: return spv::BuiltInVertexId;
506 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700507 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
508 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInBaseVertex;
514
John Kessenichda581a22015-10-14 14:10:30 -0600515 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800516 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
517 builder.addCapability(spv::CapabilityDrawParameters);
518 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200519
John Kessenichda581a22015-10-14 14:10:30 -0600520 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800521 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
522 builder.addCapability(spv::CapabilityDrawParameters);
523 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200524
525 case glslang::EbvPrimitiveId:
526 if (glslangIntermediate->getStage() == EShLangFragment)
527 builder.addCapability(spv::CapabilityGeometry);
528 return spv::BuiltInPrimitiveId;
529
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
532 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
533 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
534 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
535 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
536 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
537 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600538 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
539 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
540 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
541 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
542 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
543 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
544 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
545 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupSize;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupLocalInvocationId;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupEqMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGeMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupGtMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLeMaskKHR;
576
Rex Xu574ab042016-04-14 16:53:07 +0800577 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
579 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
580 return spv::BuiltInSubgroupLtMaskKHR;
581
Rex Xu9d93a232016-05-05 12:30:44 +0800582#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800583 case glslang::EbvBaryCoordNoPersp:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspAMD;
586
587 case glslang::EbvBaryCoordNoPerspCentroid:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
590
591 case glslang::EbvBaryCoordNoPerspSample:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordNoPerspSampleAMD;
594
595 case glslang::EbvBaryCoordSmooth:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothAMD;
598
599 case glslang::EbvBaryCoordSmoothCentroid:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordSmoothCentroidAMD;
602
603 case glslang::EbvBaryCoordSmoothSample:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordSmoothSampleAMD;
606
607 case glslang::EbvBaryCoordPullModel:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800610#endif
John Kessenich4016e382016-07-15 11:53:56 -0600611 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600612 }
613}
614
Rex Xufc618912015-09-09 16:42:49 +0800615// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700616spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800617{
618 assert(type.getBasicType() == glslang::EbtSampler);
619
John Kessenich5d0fa972016-02-15 11:57:00 -0700620 // Check for capabilities
621 switch (type.getQualifier().layoutFormat) {
622 case glslang::ElfRg32f:
623 case glslang::ElfRg16f:
624 case glslang::ElfR11fG11fB10f:
625 case glslang::ElfR16f:
626 case glslang::ElfRgba16:
627 case glslang::ElfRgb10A2:
628 case glslang::ElfRg16:
629 case glslang::ElfRg8:
630 case glslang::ElfR16:
631 case glslang::ElfR8:
632 case glslang::ElfRgba16Snorm:
633 case glslang::ElfRg16Snorm:
634 case glslang::ElfRg8Snorm:
635 case glslang::ElfR16Snorm:
636 case glslang::ElfR8Snorm:
637
638 case glslang::ElfRg32i:
639 case glslang::ElfRg16i:
640 case glslang::ElfRg8i:
641 case glslang::ElfR16i:
642 case glslang::ElfR8i:
643
644 case glslang::ElfRgb10a2ui:
645 case glslang::ElfRg32ui:
646 case glslang::ElfRg16ui:
647 case glslang::ElfRg8ui:
648 case glslang::ElfR16ui:
649 case glslang::ElfR8ui:
650 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
651 break;
652
653 default:
654 break;
655 }
656
657 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800658 switch (type.getQualifier().layoutFormat) {
659 case glslang::ElfNone: return spv::ImageFormatUnknown;
660 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
661 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
662 case glslang::ElfR32f: return spv::ImageFormatR32f;
663 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
664 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
665 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
666 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
667 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
668 case glslang::ElfR16f: return spv::ImageFormatR16f;
669 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
670 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
671 case glslang::ElfRg16: return spv::ImageFormatRg16;
672 case glslang::ElfRg8: return spv::ImageFormatRg8;
673 case glslang::ElfR16: return spv::ImageFormatR16;
674 case glslang::ElfR8: return spv::ImageFormatR8;
675 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
676 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
677 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
678 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
679 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
680 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
681 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
682 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
683 case glslang::ElfR32i: return spv::ImageFormatR32i;
684 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
685 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
686 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
687 case glslang::ElfR16i: return spv::ImageFormatR16i;
688 case glslang::ElfR8i: return spv::ImageFormatR8i;
689 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
690 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
691 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
692 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
693 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
694 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
695 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
696 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
697 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
698 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600699 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800700 }
701}
702
qining25262b32016-05-06 17:25:16 -0400703// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700704// descriptor set.
705bool IsDescriptorResource(const glslang::TType& type)
706{
John Kessenichf7497e22016-03-08 21:36:22 -0700707 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700708 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700709 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700710
711 // non block...
712 // basically samplerXXX/subpass/sampler/texture are all included
713 // if they are the global-scope-class, not the function parameter
714 // (or local, if they ever exist) class.
715 if (type.getBasicType() == glslang::EbtSampler)
716 return type.getQualifier().isUniformOrBuffer();
717
718 // None of the above.
719 return false;
720}
721
John Kesseniche0b6cad2015-12-24 10:30:13 -0700722void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
723{
724 if (child.layoutMatrix == glslang::ElmNone)
725 child.layoutMatrix = parent.layoutMatrix;
726
727 if (parent.invariant)
728 child.invariant = true;
729 if (parent.nopersp)
730 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800731#ifdef AMD_EXTENSIONS
732 if (parent.explicitInterp)
733 child.explicitInterp = true;
734#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700735 if (parent.flat)
736 child.flat = true;
737 if (parent.centroid)
738 child.centroid = true;
739 if (parent.patch)
740 child.patch = true;
741 if (parent.sample)
742 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800743 if (parent.coherent)
744 child.coherent = true;
745 if (parent.volatil)
746 child.volatil = true;
747 if (parent.restrict)
748 child.restrict = true;
749 if (parent.readonly)
750 child.readonly = true;
751 if (parent.writeonly)
752 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700753}
754
John Kessenichf2b7f332016-09-01 17:05:23 -0600755bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700756{
John Kessenich7b9fa252016-01-21 18:56:57 -0700757 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600758 // - struct members might inherit from a struct declaration
759 // (note that non-block structs don't explicitly inherit,
760 // only implicitly, meaning no decoration involved)
761 // - affect decorations on the struct members
762 // (note smooth does not, and expecting something like volatile
763 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700764 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600765 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700766}
767
John Kessenich140f3df2015-06-26 16:58:36 -0600768//
769// Implement the TGlslangToSpvTraverser class.
770//
771
Lei Zhang17535f72016-05-04 15:55:59 -0400772TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600773 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
774 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400775 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700776 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600777 glslangIntermediate(glslangIntermediate)
778{
779 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
780
781 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700782 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600783 stdBuiltins = builder.import("GLSL.std.450");
784 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600785 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
786 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600787
788 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600789 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
790 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600791 builder.addSourceExtension(it->c_str());
792
793 // Add the top-level modes for this shader.
794
John Kessenich92187592016-02-01 13:45:25 -0700795 if (glslangIntermediate->getXfbMode()) {
796 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600797 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700798 }
John Kessenich140f3df2015-06-26 16:58:36 -0600799
800 unsigned int mode;
801 switch (glslangIntermediate->getStage()) {
802 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600803 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600804 break;
805
806 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600807 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600808 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
809 break;
810
811 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600812 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600813 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700814 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
815 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
816 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600817 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600818 }
John Kessenich4016e382016-07-15 11:53:56 -0600819 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600820 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
821
John Kesseniche6903322015-10-13 16:29:02 -0600822 switch (glslangIntermediate->getVertexSpacing()) {
823 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
824 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
825 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600826 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600827 }
John Kessenich4016e382016-07-15 11:53:56 -0600828 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600829 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
830
831 switch (glslangIntermediate->getVertexOrder()) {
832 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
833 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600834 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600835 }
John Kessenich4016e382016-07-15 11:53:56 -0600836 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600837 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
838
839 if (glslangIntermediate->getPointMode())
840 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600841 break;
842
843 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600844 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600845 switch (glslangIntermediate->getInputPrimitive()) {
846 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
847 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
848 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700849 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600850 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600851 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600852 }
John Kessenich4016e382016-07-15 11:53:56 -0600853 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600854 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600855
John Kessenich140f3df2015-06-26 16:58:36 -0600856 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
857
858 switch (glslangIntermediate->getOutputPrimitive()) {
859 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
860 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
861 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600862 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600863 }
John Kessenich4016e382016-07-15 11:53:56 -0600864 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600865 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
866 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
867 break;
868
869 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600870 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600871 if (glslangIntermediate->getPixelCenterInteger())
872 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600873
John Kessenich140f3df2015-06-26 16:58:36 -0600874 if (glslangIntermediate->getOriginUpperLeft())
875 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600876 else
877 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600878
879 if (glslangIntermediate->getEarlyFragmentTests())
880 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
881
882 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600883 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
884 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600885 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600886 }
John Kessenich4016e382016-07-15 11:53:56 -0600887 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600888 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
889
890 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
891 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600892 break;
893
894 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600895 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600896 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
897 glslangIntermediate->getLocalSize(1),
898 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600899 break;
900
901 default:
902 break;
903 }
John Kessenich140f3df2015-06-26 16:58:36 -0600904}
905
John Kessenichfca82622016-11-26 13:23:20 -0700906// Finish creating SPV, after the traversal is complete.
907void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700908{
John Kessenich517fe7a2016-11-26 13:31:47 -0700909 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700910 builder.setBuildPoint(shaderEntry->getLastBlock());
911 builder.leaveFunction();
912 }
913
John Kessenich7ba63412015-12-20 17:37:07 -0700914 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100915 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
916 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700917
qiningda397332016-03-09 19:54:03 -0500918 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700919}
920
John Kessenichfca82622016-11-26 13:23:20 -0700921// Write the SPV into 'out'.
922void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600923{
John Kessenichfca82622016-11-26 13:23:20 -0700924 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600925}
926
927//
928// Implement the traversal functions.
929//
930// Return true from interior nodes to have the external traversal
931// continue on to children. Return false if children were
932// already processed.
933//
934
935//
qining25262b32016-05-06 17:25:16 -0400936// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600937// - uniform/input reads
938// - output writes
939// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
940// - something simple that degenerates into the last bullet
941//
942void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
943{
qining75d1d802016-04-06 14:42:01 -0400944 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
945 if (symbol->getType().getQualifier().isSpecConstant())
946 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
947
John Kessenich140f3df2015-06-26 16:58:36 -0600948 // getSymbolId() will set up all the IO decorations on the first call.
949 // Formal function parameters were mapped during makeFunctions().
950 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700951
952 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
953 if (builder.isPointer(id)) {
954 spv::StorageClass sc = builder.getStorageClass(id);
955 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
956 iOSet.insert(id);
957 }
958
959 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700960 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600961 // Prepare to generate code for the access
962
963 // L-value chains will be computed left to right. We're on the symbol now,
964 // which is the left-most part of the access chain, so now is "clear" time,
965 // followed by setting the base.
966 builder.clearAccessChain();
967
968 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700969 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600970 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700971 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600972 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700973 // These are also pure R-values.
974 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600975 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600976 builder.setAccessChainRValue(id);
977 else
978 builder.setAccessChainLValue(id);
979 }
980}
981
982bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
983{
qining40887662016-04-03 22:20:42 -0400984 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
985 if (node->getType().getQualifier().isSpecConstant())
986 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
987
John Kessenich140f3df2015-06-26 16:58:36 -0600988 // First, handle special cases
989 switch (node->getOp()) {
990 case glslang::EOpAssign:
991 case glslang::EOpAddAssign:
992 case glslang::EOpSubAssign:
993 case glslang::EOpMulAssign:
994 case glslang::EOpVectorTimesMatrixAssign:
995 case glslang::EOpVectorTimesScalarAssign:
996 case glslang::EOpMatrixTimesScalarAssign:
997 case glslang::EOpMatrixTimesMatrixAssign:
998 case glslang::EOpDivAssign:
999 case glslang::EOpModAssign:
1000 case glslang::EOpAndAssign:
1001 case glslang::EOpInclusiveOrAssign:
1002 case glslang::EOpExclusiveOrAssign:
1003 case glslang::EOpLeftShiftAssign:
1004 case glslang::EOpRightShiftAssign:
1005 // A bin-op assign "a += b" means the same thing as "a = a + b"
1006 // where a is evaluated before b. For a simple assignment, GLSL
1007 // says to evaluate the left before the right. So, always, left
1008 // node then right node.
1009 {
1010 // get the left l-value, save it away
1011 builder.clearAccessChain();
1012 node->getLeft()->traverse(this);
1013 spv::Builder::AccessChain lValue = builder.getAccessChain();
1014
1015 // evaluate the right
1016 builder.clearAccessChain();
1017 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001018 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001019
1020 if (node->getOp() != glslang::EOpAssign) {
1021 // the left is also an r-value
1022 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001023 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001024
1025 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001026 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001027 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001028 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1029 node->getType().getBasicType());
1030
1031 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001032 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001033 }
1034
1035 // store the result
1036 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001037 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001038
1039 // assignments are expressions having an rValue after they are evaluated...
1040 builder.clearAccessChain();
1041 builder.setAccessChainRValue(rValue);
1042 }
1043 return false;
1044 case glslang::EOpIndexDirect:
1045 case glslang::EOpIndexDirectStruct:
1046 {
1047 // Get the left part of the access chain.
1048 node->getLeft()->traverse(this);
1049
1050 // Add the next element in the chain
1051
David Netoa901ffe2016-06-08 14:11:40 +01001052 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001053 if (! node->getLeft()->getType().isArray() &&
1054 node->getLeft()->getType().isVector() &&
1055 node->getOp() == glslang::EOpIndexDirect) {
1056 // This is essentially a hard-coded vector swizzle of size 1,
1057 // so short circuit the access-chain stuff with a swizzle.
1058 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001059 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001060 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001061 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001062 int spvIndex = glslangIndex;
1063 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1064 node->getOp() == glslang::EOpIndexDirectStruct)
1065 {
1066 // This may be, e.g., an anonymous block-member selection, which generally need
1067 // index remapping due to hidden members in anonymous blocks.
1068 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1069 assert(remapper.size() > 0);
1070 spvIndex = remapper[glslangIndex];
1071 }
John Kessenichebb50532016-05-16 19:22:05 -06001072
David Netoa901ffe2016-06-08 14:11:40 +01001073 // normal case for indexing array or structure or block
1074 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1075
1076 // Add capabilities here for accessing PointSize and clip/cull distance.
1077 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001078 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001079 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001080 }
1081 }
1082 return false;
1083 case glslang::EOpIndexIndirect:
1084 {
1085 // Structure or array or vector indirection.
1086 // Will use native SPIR-V access-chain for struct and array indirection;
1087 // matrices are arrays of vectors, so will also work for a matrix.
1088 // Will use the access chain's 'component' for variable index into a vector.
1089
1090 // This adapter is building access chains left to right.
1091 // Set up the access chain to the left.
1092 node->getLeft()->traverse(this);
1093
1094 // save it so that computing the right side doesn't trash it
1095 spv::Builder::AccessChain partial = builder.getAccessChain();
1096
1097 // compute the next index in the chain
1098 builder.clearAccessChain();
1099 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001100 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001101
1102 // restore the saved access chain
1103 builder.setAccessChain(partial);
1104
1105 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001106 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001107 else
John Kessenichfa668da2015-09-13 14:46:30 -06001108 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001109 }
1110 return false;
1111 case glslang::EOpVectorSwizzle:
1112 {
1113 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001114 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001115 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001116 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001117 }
1118 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001119 case glslang::EOpLogicalOr:
1120 case glslang::EOpLogicalAnd:
1121 {
1122
1123 // These may require short circuiting, but can sometimes be done as straight
1124 // binary operations. The right operand must be short circuited if it has
1125 // side effects, and should probably be if it is complex.
1126 if (isTrivial(node->getRight()->getAsTyped()))
1127 break; // handle below as a normal binary operation
1128 // otherwise, we need to do dynamic short circuiting on the right operand
1129 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1130 builder.clearAccessChain();
1131 builder.setAccessChainRValue(result);
1132 }
1133 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001134 default:
1135 break;
1136 }
1137
1138 // Assume generic binary op...
1139
John Kessenich32cfd492016-02-02 12:37:46 -07001140 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001141 builder.clearAccessChain();
1142 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001143 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
John Kessenich32cfd492016-02-02 12:37:46 -07001145 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001146 builder.clearAccessChain();
1147 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001148 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001149
John Kessenich32cfd492016-02-02 12:37:46 -07001150 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001151 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001152 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001153 convertGlslangToSpvType(node->getType()), left, right,
1154 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001155
John Kessenich50e57562015-12-21 21:21:11 -07001156 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001157 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001158 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001159 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001160 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001161 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001162 return false;
1163 }
John Kessenich140f3df2015-06-26 16:58:36 -06001164}
1165
1166bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1167{
qining40887662016-04-03 22:20:42 -04001168 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1169 if (node->getType().getQualifier().isSpecConstant())
1170 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1171
John Kessenichfc51d282015-08-19 13:34:18 -06001172 spv::Id result = spv::NoResult;
1173
1174 // try texturing first
1175 result = createImageTextureFunctionCall(node);
1176 if (result != spv::NoResult) {
1177 builder.clearAccessChain();
1178 builder.setAccessChainRValue(result);
1179
1180 return false; // done with this node
1181 }
1182
1183 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001184
1185 if (node->getOp() == glslang::EOpArrayLength) {
1186 // Quite special; won't want to evaluate the operand.
1187
1188 // Normal .length() would have been constant folded by the front-end.
1189 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001190 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001191 assert(node->getOperand()->getType().isRuntimeSizedArray());
1192 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1193 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001194 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1195 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001196
1197 builder.clearAccessChain();
1198 builder.setAccessChainRValue(length);
1199
1200 return false;
1201 }
1202
John Kessenichfc51d282015-08-19 13:34:18 -06001203 // Start by evaluating the operand
1204
John Kessenich8c8505c2016-07-26 12:50:38 -06001205 // Does it need a swizzle inversion? If so, evaluation is inverted;
1206 // operate first on the swizzle base, then apply the swizzle.
1207 spv::Id invertedType = spv::NoType;
1208 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1209 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1210 invertedType = getInvertedSwizzleType(*node->getOperand());
1211
John Kessenich140f3df2015-06-26 16:58:36 -06001212 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001213 if (invertedType != spv::NoType)
1214 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1215 else
1216 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001217
Rex Xufc618912015-09-09 16:42:49 +08001218 spv::Id operand = spv::NoResult;
1219
1220 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1221 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001222 node->getOp() == glslang::EOpAtomicCounter ||
1223 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001224 operand = builder.accessChainGetLValue(); // Special case l-value operands
1225 else
John Kessenich32cfd492016-02-02 12:37:46 -07001226 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001227
John Kessenichf6640762016-08-01 19:44:00 -06001228 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001229 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001230
1231 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001232 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001233 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001234
1235 // if not, then possibly an operation
1236 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001237 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001238
1239 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001240 if (invertedType)
1241 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1242
John Kessenich140f3df2015-06-26 16:58:36 -06001243 builder.clearAccessChain();
1244 builder.setAccessChainRValue(result);
1245
1246 return false; // done with this node
1247 }
1248
1249 // it must be a special case, check...
1250 switch (node->getOp()) {
1251 case glslang::EOpPostIncrement:
1252 case glslang::EOpPostDecrement:
1253 case glslang::EOpPreIncrement:
1254 case glslang::EOpPreDecrement:
1255 {
1256 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001257 spv::Id one = 0;
1258 if (node->getBasicType() == glslang::EbtFloat)
1259 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001260 else if (node->getBasicType() == glslang::EbtDouble)
1261 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001262#ifdef AMD_EXTENSIONS
1263 else if (node->getBasicType() == glslang::EbtFloat16)
1264 one = builder.makeFloat16Constant(1.0F);
1265#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001266 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1267 one = builder.makeInt64Constant(1);
1268 else
1269 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001270 glslang::TOperator op;
1271 if (node->getOp() == glslang::EOpPreIncrement ||
1272 node->getOp() == glslang::EOpPostIncrement)
1273 op = glslang::EOpAdd;
1274 else
1275 op = glslang::EOpSub;
1276
John Kessenichf6640762016-08-01 19:44:00 -06001277 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001278 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001279 convertGlslangToSpvType(node->getType()), operand, one,
1280 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001281 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001282
1283 // The result of operation is always stored, but conditionally the
1284 // consumed result. The consumed result is always an r-value.
1285 builder.accessChainStore(result);
1286 builder.clearAccessChain();
1287 if (node->getOp() == glslang::EOpPreIncrement ||
1288 node->getOp() == glslang::EOpPreDecrement)
1289 builder.setAccessChainRValue(result);
1290 else
1291 builder.setAccessChainRValue(operand);
1292 }
1293
1294 return false;
1295
1296 case glslang::EOpEmitStreamVertex:
1297 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1298 return false;
1299 case glslang::EOpEndStreamPrimitive:
1300 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1301 return false;
1302
1303 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001304 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001305 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001306 }
John Kessenich140f3df2015-06-26 16:58:36 -06001307}
1308
1309bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1310{
qining27e04a02016-04-14 16:40:20 -04001311 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1312 if (node->getType().getQualifier().isSpecConstant())
1313 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1314
John Kessenichfc51d282015-08-19 13:34:18 -06001315 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001316 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1317 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001318
1319 // try texturing
1320 result = createImageTextureFunctionCall(node);
1321 if (result != spv::NoResult) {
1322 builder.clearAccessChain();
1323 builder.setAccessChainRValue(result);
1324
1325 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001326 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001327 // "imageStore" is a special case, which has no result
1328 return false;
1329 }
John Kessenichfc51d282015-08-19 13:34:18 -06001330
John Kessenich140f3df2015-06-26 16:58:36 -06001331 glslang::TOperator binOp = glslang::EOpNull;
1332 bool reduceComparison = true;
1333 bool isMatrix = false;
1334 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001335 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001336
1337 assert(node->getOp());
1338
John Kessenichf6640762016-08-01 19:44:00 -06001339 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001340
1341 switch (node->getOp()) {
1342 case glslang::EOpSequence:
1343 {
1344 if (preVisit)
1345 ++sequenceDepth;
1346 else
1347 --sequenceDepth;
1348
1349 if (sequenceDepth == 1) {
1350 // If this is the parent node of all the functions, we want to see them
1351 // early, so all call points have actual SPIR-V functions to reference.
1352 // In all cases, still let the traverser visit the children for us.
1353 makeFunctions(node->getAsAggregate()->getSequence());
1354
John Kessenich6fccb3c2016-09-19 16:01:41 -06001355 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001356 // anything else gets there, so visit out of order, doing them all now.
1357 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1358
John Kessenich6a60c2f2016-12-08 21:01:59 -07001359 // 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 -06001360 // so do them manually.
1361 visitFunctions(node->getAsAggregate()->getSequence());
1362
1363 return false;
1364 }
1365
1366 return true;
1367 }
1368 case glslang::EOpLinkerObjects:
1369 {
1370 if (visit == glslang::EvPreVisit)
1371 linkageOnly = true;
1372 else
1373 linkageOnly = false;
1374
1375 return true;
1376 }
1377 case glslang::EOpComma:
1378 {
1379 // processing from left to right naturally leaves the right-most
1380 // lying around in the access chain
1381 glslang::TIntermSequence& glslangOperands = node->getSequence();
1382 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1383 glslangOperands[i]->traverse(this);
1384
1385 return false;
1386 }
1387 case glslang::EOpFunction:
1388 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001389 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001390 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001391 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001392 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001393 } else {
1394 handleFunctionEntry(node);
1395 }
1396 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001397 if (inEntryPoint)
1398 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001399 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001400 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001401 }
1402
1403 return true;
1404 case glslang::EOpParameters:
1405 // Parameters will have been consumed by EOpFunction processing, but not
1406 // the body, so we still visited the function node's children, making this
1407 // child redundant.
1408 return false;
1409 case glslang::EOpFunctionCall:
1410 {
1411 if (node->isUserDefined())
1412 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001413 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1414 if (result) {
1415 builder.clearAccessChain();
1416 builder.setAccessChainRValue(result);
1417 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001418 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001419
1420 return false;
1421 }
1422 case glslang::EOpConstructMat2x2:
1423 case glslang::EOpConstructMat2x3:
1424 case glslang::EOpConstructMat2x4:
1425 case glslang::EOpConstructMat3x2:
1426 case glslang::EOpConstructMat3x3:
1427 case glslang::EOpConstructMat3x4:
1428 case glslang::EOpConstructMat4x2:
1429 case glslang::EOpConstructMat4x3:
1430 case glslang::EOpConstructMat4x4:
1431 case glslang::EOpConstructDMat2x2:
1432 case glslang::EOpConstructDMat2x3:
1433 case glslang::EOpConstructDMat2x4:
1434 case glslang::EOpConstructDMat3x2:
1435 case glslang::EOpConstructDMat3x3:
1436 case glslang::EOpConstructDMat3x4:
1437 case glslang::EOpConstructDMat4x2:
1438 case glslang::EOpConstructDMat4x3:
1439 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001440#ifdef AMD_EXTENSIONS
1441 case glslang::EOpConstructF16Mat2x2:
1442 case glslang::EOpConstructF16Mat2x3:
1443 case glslang::EOpConstructF16Mat2x4:
1444 case glslang::EOpConstructF16Mat3x2:
1445 case glslang::EOpConstructF16Mat3x3:
1446 case glslang::EOpConstructF16Mat3x4:
1447 case glslang::EOpConstructF16Mat4x2:
1448 case glslang::EOpConstructF16Mat4x3:
1449 case glslang::EOpConstructF16Mat4x4:
1450#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001451 isMatrix = true;
1452 // fall through
1453 case glslang::EOpConstructFloat:
1454 case glslang::EOpConstructVec2:
1455 case glslang::EOpConstructVec3:
1456 case glslang::EOpConstructVec4:
1457 case glslang::EOpConstructDouble:
1458 case glslang::EOpConstructDVec2:
1459 case glslang::EOpConstructDVec3:
1460 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001461#ifdef AMD_EXTENSIONS
1462 case glslang::EOpConstructFloat16:
1463 case glslang::EOpConstructF16Vec2:
1464 case glslang::EOpConstructF16Vec3:
1465 case glslang::EOpConstructF16Vec4:
1466#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001467 case glslang::EOpConstructBool:
1468 case glslang::EOpConstructBVec2:
1469 case glslang::EOpConstructBVec3:
1470 case glslang::EOpConstructBVec4:
1471 case glslang::EOpConstructInt:
1472 case glslang::EOpConstructIVec2:
1473 case glslang::EOpConstructIVec3:
1474 case glslang::EOpConstructIVec4:
1475 case glslang::EOpConstructUint:
1476 case glslang::EOpConstructUVec2:
1477 case glslang::EOpConstructUVec3:
1478 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001479 case glslang::EOpConstructInt64:
1480 case glslang::EOpConstructI64Vec2:
1481 case glslang::EOpConstructI64Vec3:
1482 case glslang::EOpConstructI64Vec4:
1483 case glslang::EOpConstructUint64:
1484 case glslang::EOpConstructU64Vec2:
1485 case glslang::EOpConstructU64Vec3:
1486 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001487 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001488 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001489 {
1490 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001491 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001492 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001493 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001494 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001495 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001496 std::vector<spv::Id> constituents;
1497 for (int c = 0; c < (int)arguments.size(); ++c)
1498 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001499 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001500 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001501 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001502 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001503 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 builder.clearAccessChain();
1506 builder.setAccessChainRValue(constructed);
1507
1508 return false;
1509 }
1510
1511 // These six are component-wise compares with component-wise results.
1512 // Forward on to createBinaryOperation(), requesting a vector result.
1513 case glslang::EOpLessThan:
1514 case glslang::EOpGreaterThan:
1515 case glslang::EOpLessThanEqual:
1516 case glslang::EOpGreaterThanEqual:
1517 case glslang::EOpVectorEqual:
1518 case glslang::EOpVectorNotEqual:
1519 {
1520 // Map the operation to a binary
1521 binOp = node->getOp();
1522 reduceComparison = false;
1523 switch (node->getOp()) {
1524 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1525 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1526 default: binOp = node->getOp(); break;
1527 }
1528
1529 break;
1530 }
1531 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001532 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001533 binOp = glslang::EOpMul;
1534 break;
1535 case glslang::EOpOuterProduct:
1536 // two vectors multiplied to make a matrix
1537 binOp = glslang::EOpOuterProduct;
1538 break;
1539 case glslang::EOpDot:
1540 {
qining25262b32016-05-06 17:25:16 -04001541 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001542 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001543 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001544 binOp = glslang::EOpMul;
1545 break;
1546 }
1547 case glslang::EOpMod:
1548 // when an aggregate, this is the floating-point mod built-in function,
1549 // which can be emitted by the one in createBinaryOperation()
1550 binOp = glslang::EOpMod;
1551 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001552 case glslang::EOpEmitVertex:
1553 case glslang::EOpEndPrimitive:
1554 case glslang::EOpBarrier:
1555 case glslang::EOpMemoryBarrier:
1556 case glslang::EOpMemoryBarrierAtomicCounter:
1557 case glslang::EOpMemoryBarrierBuffer:
1558 case glslang::EOpMemoryBarrierImage:
1559 case glslang::EOpMemoryBarrierShared:
1560 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001561 case glslang::EOpAllMemoryBarrierWithGroupSync:
1562 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1563 case glslang::EOpWorkgroupMemoryBarrier:
1564 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001565 noReturnValue = true;
1566 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1567 break;
1568
John Kessenich426394d2015-07-23 10:22:48 -06001569 case glslang::EOpAtomicAdd:
1570 case glslang::EOpAtomicMin:
1571 case glslang::EOpAtomicMax:
1572 case glslang::EOpAtomicAnd:
1573 case glslang::EOpAtomicOr:
1574 case glslang::EOpAtomicXor:
1575 case glslang::EOpAtomicExchange:
1576 case glslang::EOpAtomicCompSwap:
1577 atomic = true;
1578 break;
1579
John Kessenich140f3df2015-06-26 16:58:36 -06001580 default:
1581 break;
1582 }
1583
1584 //
1585 // See if it maps to a regular operation.
1586 //
John Kessenich140f3df2015-06-26 16:58:36 -06001587 if (binOp != glslang::EOpNull) {
1588 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1589 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1590 assert(left && right);
1591
1592 builder.clearAccessChain();
1593 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001594 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001595
1596 builder.clearAccessChain();
1597 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001598 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001599
qining25262b32016-05-06 17:25:16 -04001600 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001601 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001602 left->getType().getBasicType(), reduceComparison);
1603
1604 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001605 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 builder.clearAccessChain();
1607 builder.setAccessChainRValue(result);
1608
1609 return false;
1610 }
1611
John Kessenich426394d2015-07-23 10:22:48 -06001612 //
1613 // Create the list of operands.
1614 //
John Kessenich140f3df2015-06-26 16:58:36 -06001615 glslang::TIntermSequence& glslangOperands = node->getSequence();
1616 std::vector<spv::Id> operands;
1617 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001618 // special case l-value operands; there are just a few
1619 bool lvalue = false;
1620 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001621 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001622 case glslang::EOpModf:
1623 if (arg == 1)
1624 lvalue = true;
1625 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001626 case glslang::EOpInterpolateAtSample:
1627 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001628#ifdef AMD_EXTENSIONS
1629 case glslang::EOpInterpolateAtVertex:
1630#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001631 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001632 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001633
1634 // Does it need a swizzle inversion? If so, evaluation is inverted;
1635 // operate first on the swizzle base, then apply the swizzle.
1636 if (glslangOperands[0]->getAsOperator() &&
1637 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1638 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1639 }
Rex Xu7a26c172015-12-08 17:12:09 +08001640 break;
Rex Xud4782c12015-09-06 16:30:11 +08001641 case glslang::EOpAtomicAdd:
1642 case glslang::EOpAtomicMin:
1643 case glslang::EOpAtomicMax:
1644 case glslang::EOpAtomicAnd:
1645 case glslang::EOpAtomicOr:
1646 case glslang::EOpAtomicXor:
1647 case glslang::EOpAtomicExchange:
1648 case glslang::EOpAtomicCompSwap:
1649 if (arg == 0)
1650 lvalue = true;
1651 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001652 case glslang::EOpAddCarry:
1653 case glslang::EOpSubBorrow:
1654 if (arg == 2)
1655 lvalue = true;
1656 break;
1657 case glslang::EOpUMulExtended:
1658 case glslang::EOpIMulExtended:
1659 if (arg >= 2)
1660 lvalue = true;
1661 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001662 default:
1663 break;
1664 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001665 builder.clearAccessChain();
1666 if (invertedType != spv::NoType && arg == 0)
1667 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1668 else
1669 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 if (lvalue)
1671 operands.push_back(builder.accessChainGetLValue());
1672 else
John Kessenich32cfd492016-02-02 12:37:46 -07001673 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001674 }
John Kessenich426394d2015-07-23 10:22:48 -06001675
1676 if (atomic) {
1677 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001678 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001679 } else {
1680 // Pass through to generic operations.
1681 switch (glslangOperands.size()) {
1682 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001683 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001684 break;
1685 case 1:
qining25262b32016-05-06 17:25:16 -04001686 result = createUnaryOperation(
1687 node->getOp(), precision,
1688 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001689 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001690 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001691 break;
1692 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001693 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001694 break;
1695 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001696 if (invertedType)
1697 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001698 }
1699
1700 if (noReturnValue)
1701 return false;
1702
1703 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001704 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001705 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001706 } else {
1707 builder.clearAccessChain();
1708 builder.setAccessChainRValue(result);
1709 return false;
1710 }
1711}
1712
1713bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1714{
1715 // This path handles both if-then-else and ?:
1716 // The if-then-else has a node type of void, while
1717 // ?: has a non-void node type
1718 spv::Id result = 0;
1719 if (node->getBasicType() != glslang::EbtVoid) {
1720 // don't handle this as just on-the-fly temporaries, because there will be two names
1721 // and better to leave SSA to later passes
1722 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1723 }
1724
1725 // emit the condition before doing anything with selection
1726 node->getCondition()->traverse(this);
1727
1728 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001729 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001730
1731 if (node->getTrueBlock()) {
1732 // emit the "then" statement
1733 node->getTrueBlock()->traverse(this);
1734 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001735 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001736 }
1737
1738 if (node->getFalseBlock()) {
1739 ifBuilder.makeBeginElse();
1740 // emit the "else" statement
1741 node->getFalseBlock()->traverse(this);
1742 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001743 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 }
1745
1746 ifBuilder.makeEndIf();
1747
1748 if (result) {
1749 // GLSL only has r-values as the result of a :?, but
1750 // if we have an l-value, that can be more efficient if it will
1751 // become the base of a complex r-value expression, because the
1752 // next layer copies r-values into memory to use the access-chain mechanism
1753 builder.clearAccessChain();
1754 builder.setAccessChainLValue(result);
1755 }
1756
1757 return false;
1758}
1759
1760bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1761{
1762 // emit and get the condition before doing anything with switch
1763 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001764 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001765
1766 // browse the children to sort out code segments
1767 int defaultSegment = -1;
1768 std::vector<TIntermNode*> codeSegments;
1769 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1770 std::vector<int> caseValues;
1771 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1772 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1773 TIntermNode* child = *c;
1774 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001775 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001776 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001777 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001778 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1779 } else
1780 codeSegments.push_back(child);
1781 }
1782
qining25262b32016-05-06 17:25:16 -04001783 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001784 // statements between the last case and the end of the switch statement
1785 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1786 (int)codeSegments.size() == defaultSegment)
1787 codeSegments.push_back(nullptr);
1788
1789 // make the switch statement
1790 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001791 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001792
1793 // emit all the code in the segments
1794 breakForLoop.push(false);
1795 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1796 builder.nextSwitchSegment(segmentBlocks, s);
1797 if (codeSegments[s])
1798 codeSegments[s]->traverse(this);
1799 else
1800 builder.addSwitchBreak();
1801 }
1802 breakForLoop.pop();
1803
1804 builder.endSwitch(segmentBlocks);
1805
1806 return false;
1807}
1808
1809void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1810{
1811 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001812 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001813
1814 builder.clearAccessChain();
1815 builder.setAccessChainRValue(constant);
1816}
1817
1818bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1819{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001820 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001821 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001822 // Spec requires back edges to target header blocks, and every header block
1823 // must dominate its merge block. Make a header block first to ensure these
1824 // conditions are met. By definition, it will contain OpLoopMerge, followed
1825 // by a block-ending branch. But we don't want to put any other body/test
1826 // instructions in it, since the body/test may have arbitrary instructions,
1827 // including merges of its own.
1828 builder.setBuildPoint(&blocks.head);
1829 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001830 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001831 spv::Block& test = builder.makeNewBlock();
1832 builder.createBranch(&test);
1833
1834 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001835 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001836 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001837 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001838 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1839
1840 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001841 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001842 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001843 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001844 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001845 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001846
1847 builder.setBuildPoint(&blocks.continue_target);
1848 if (node->getTerminal())
1849 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001850 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001851 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001852 builder.createBranch(&blocks.body);
1853
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001854 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001855 builder.setBuildPoint(&blocks.body);
1856 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001857 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001858 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001859 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001860
1861 builder.setBuildPoint(&blocks.continue_target);
1862 if (node->getTerminal())
1863 node->getTerminal()->traverse(this);
1864 if (node->getTest()) {
1865 node->getTest()->traverse(this);
1866 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001867 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001868 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001869 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001870 // TODO: unless there was a break/return/discard instruction
1871 // somewhere in the body, this is an infinite loop, so we should
1872 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001873 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001874 }
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001876 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001877 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001878 return false;
1879}
1880
1881bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1882{
1883 if (node->getExpression())
1884 node->getExpression()->traverse(this);
1885
1886 switch (node->getFlowOp()) {
1887 case glslang::EOpKill:
1888 builder.makeDiscard();
1889 break;
1890 case glslang::EOpBreak:
1891 if (breakForLoop.top())
1892 builder.createLoopExit();
1893 else
1894 builder.addSwitchBreak();
1895 break;
1896 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001897 builder.createLoopContinue();
1898 break;
1899 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001900 if (node->getExpression()) {
1901 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1902 spv::Id returnId = accessChainLoad(glslangReturnType);
1903 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1904 builder.clearAccessChain();
1905 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1906 builder.setAccessChainLValue(copyId);
1907 multiTypeStore(glslangReturnType, returnId);
1908 returnId = builder.createLoad(copyId);
1909 }
1910 builder.makeReturn(false, returnId);
1911 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001912 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001913
1914 builder.clearAccessChain();
1915 break;
1916
1917 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001918 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 break;
1920 }
1921
1922 return false;
1923}
1924
1925spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1926{
qining25262b32016-05-06 17:25:16 -04001927 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001928 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001929 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001930 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001931 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001932 }
1933
1934 // Now, handle actual variables
1935 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1936 spv::Id spvType = convertGlslangToSpvType(node->getType());
1937
1938 const char* name = node->getName().c_str();
1939 if (glslang::IsAnonymous(name))
1940 name = "";
1941
1942 return builder.createVariable(storageClass, spvType, name);
1943}
1944
1945// Return type Id of the sampled type.
1946spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1947{
1948 switch (sampler.type) {
1949 case glslang::EbtFloat: return builder.makeFloatType(32);
1950 case glslang::EbtInt: return builder.makeIntType(32);
1951 case glslang::EbtUint: return builder.makeUintType(32);
1952 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001953 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001954 return builder.makeFloatType(32);
1955 }
1956}
1957
John Kessenich8c8505c2016-07-26 12:50:38 -06001958// If node is a swizzle operation, return the type that should be used if
1959// the swizzle base is first consumed by another operation, before the swizzle
1960// is applied.
1961spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1962{
1963 if (node.getAsOperator() &&
1964 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1965 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1966 else
1967 return spv::NoType;
1968}
1969
1970// When inverting a swizzle with a parent op, this function
1971// will apply the swizzle operation to a completed parent operation.
1972spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1973{
1974 std::vector<unsigned> swizzle;
1975 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1976 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1977}
1978
John Kessenich8c8505c2016-07-26 12:50:38 -06001979// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1980void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1981{
1982 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1983 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1984 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1985}
1986
John Kessenich3ac051e2015-12-20 11:29:16 -07001987// Convert from a glslang type to an SPV type, by calling into a
1988// recursive version of this function. This establishes the inherited
1989// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001990spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1991{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001992 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001993}
1994
1995// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001996// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001997// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001998spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001999{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002000 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002001
2002 switch (type.getBasicType()) {
2003 case glslang::EbtVoid:
2004 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002005 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002006 break;
2007 case glslang::EbtFloat:
2008 spvType = builder.makeFloatType(32);
2009 break;
2010 case glslang::EbtDouble:
2011 spvType = builder.makeFloatType(64);
2012 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002013#ifdef AMD_EXTENSIONS
2014 case glslang::EbtFloat16:
2015 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2016 builder.addCapability(spv::CapabilityFloat16);
2017 spvType = builder.makeFloatType(16);
2018 break;
2019#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002020 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002021 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2022 // a 32-bit int where non-0 means true.
2023 if (explicitLayout != glslang::ElpNone)
2024 spvType = builder.makeUintType(32);
2025 else
2026 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002027 break;
2028 case glslang::EbtInt:
2029 spvType = builder.makeIntType(32);
2030 break;
2031 case glslang::EbtUint:
2032 spvType = builder.makeUintType(32);
2033 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002034 case glslang::EbtInt64:
2035 builder.addCapability(spv::CapabilityInt64);
2036 spvType = builder.makeIntType(64);
2037 break;
2038 case glslang::EbtUint64:
2039 builder.addCapability(spv::CapabilityInt64);
2040 spvType = builder.makeUintType(64);
2041 break;
John Kessenich426394d2015-07-23 10:22:48 -06002042 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002043 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002044 spvType = builder.makeUintType(32);
2045 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002046 case glslang::EbtSampler:
2047 {
2048 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002049 if (sampler.sampler) {
2050 // pure sampler
2051 spvType = builder.makeSamplerType();
2052 } else {
2053 // an image is present, make its type
2054 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2055 sampler.image ? 2 : 1, TranslateImageFormat(type));
2056 if (sampler.combined) {
2057 // already has both image and sampler, make the combined type
2058 spvType = builder.makeSampledImageType(spvType);
2059 }
John Kessenich55e7d112015-11-15 21:33:39 -07002060 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002061 }
John Kessenich140f3df2015-06-26 16:58:36 -06002062 break;
2063 case glslang::EbtStruct:
2064 case glslang::EbtBlock:
2065 {
2066 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002067 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002068
2069 // Try to share structs for different layouts, but not yet for other
2070 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002071 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002072 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002073 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002074 break;
2075
2076 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002077 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002078 memberRemapper[glslangMembers].resize(glslangMembers->size());
2079 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002080 }
2081 break;
2082 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002083 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002084 break;
2085 }
2086
2087 if (type.isMatrix())
2088 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2089 else {
2090 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2091 if (type.getVectorSize() > 1)
2092 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2093 }
2094
2095 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002096 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2097
John Kessenichc9a80832015-09-12 12:17:44 -06002098 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002099 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002100 // We need to decorate array strides for types needing explicit layout, except blocks.
2101 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002102 // Use a dummy glslang type for querying internal strides of
2103 // arrays of arrays, but using just a one-dimensional array.
2104 glslang::TType simpleArrayType(type, 0); // deference type of the array
2105 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2106 simpleArrayType.getArraySizes().dereference();
2107
2108 // Will compute the higher-order strides here, rather than making a whole
2109 // pile of types and doing repetitive recursion on their contents.
2110 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2111 }
John Kessenichf8842e52016-01-04 19:22:56 -07002112
2113 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002114 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002115 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002116 if (stride > 0)
2117 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002118 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002119 }
2120 } else {
2121 // single-dimensional array, and don't yet have stride
2122
John Kessenichf8842e52016-01-04 19:22:56 -07002123 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002124 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2125 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002126 }
John Kessenich31ed4832015-09-09 17:51:38 -06002127
John Kessenichc9a80832015-09-12 12:17:44 -06002128 // Do the outer dimension, which might not be known for a runtime-sized array
2129 if (type.isRuntimeSizedArray()) {
2130 spvType = builder.makeRuntimeArray(spvType);
2131 } else {
2132 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002133 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002134 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002135 if (stride > 0)
2136 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002137 }
2138
2139 return spvType;
2140}
2141
John Kessenich6090df02016-06-30 21:18:02 -06002142
2143// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2144// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2145// Mutually recursive with convertGlslangToSpvType().
2146spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2147 const glslang::TTypeList* glslangMembers,
2148 glslang::TLayoutPacking explicitLayout,
2149 const glslang::TQualifier& qualifier)
2150{
2151 // Create a vector of struct types for SPIR-V to consume
2152 std::vector<spv::Id> spvMembers;
2153 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2154 int locationOffset = 0; // for use across struct members, when they are called recursively
2155 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2156 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2157 if (glslangMember.hiddenMember()) {
2158 ++memberDelta;
2159 if (type.getBasicType() == glslang::EbtBlock)
2160 memberRemapper[glslangMembers][i] = -1;
2161 } else {
2162 if (type.getBasicType() == glslang::EbtBlock)
2163 memberRemapper[glslangMembers][i] = i - memberDelta;
2164 // modify just this child's view of the qualifier
2165 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2166 InheritQualifiers(memberQualifier, qualifier);
2167
2168 // manually inherit location; it's more complex
2169 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2170 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2171 if (qualifier.hasLocation())
2172 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2173
2174 // recurse
2175 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2176 }
2177 }
2178
2179 // Make the SPIR-V type
2180 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002181 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002182 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2183
2184 // Decorate it
2185 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2186
2187 return spvType;
2188}
2189
2190void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2191 const glslang::TTypeList* glslangMembers,
2192 glslang::TLayoutPacking explicitLayout,
2193 const glslang::TQualifier& qualifier,
2194 spv::Id spvType)
2195{
2196 // Name and decorate the non-hidden members
2197 int offset = -1;
2198 int locationOffset = 0; // for use within the members of this struct
2199 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2200 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2201 int member = i;
2202 if (type.getBasicType() == glslang::EbtBlock)
2203 member = memberRemapper[glslangMembers][i];
2204
2205 // modify just this child's view of the qualifier
2206 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2207 InheritQualifiers(memberQualifier, qualifier);
2208
2209 // using -1 above to indicate a hidden member
2210 if (member >= 0) {
2211 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2212 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2213 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2214 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2215 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2216 if (type.getBasicType() == glslang::EbtBlock) {
2217 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2218 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2219 }
2220 }
2221 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2222
2223 if (qualifier.storage == glslang::EvqBuffer) {
2224 std::vector<spv::Decoration> memory;
2225 TranslateMemoryDecoration(memberQualifier, memory);
2226 for (unsigned int i = 0; i < memory.size(); ++i)
2227 addMemberDecoration(spvType, member, memory[i]);
2228 }
2229
John Kessenich2f47bc92016-06-30 21:47:35 -06002230 // Compute location decoration; tricky based on whether inheritance is at play and
2231 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002232 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2233 // probably move to the linker stage of the front end proper, and just have the
2234 // answer sitting already distributed throughout the individual member locations.
2235 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002236 // Ignore member locations if the container is an array, as that's
2237 // ill-specified and decisions have been made to not allow this anyway.
2238 // The object itself must have a location, and that comes out from decorating the object,
2239 // not the type (this code decorates types).
2240 if (! type.isArray()) {
2241 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2242 // struct members should not have explicit locations
2243 assert(type.getBasicType() != glslang::EbtStruct);
2244 location = memberQualifier.layoutLocation;
2245 } else if (type.getBasicType() != glslang::EbtBlock) {
2246 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2247 // The members, and their nested types, must not themselves have Location decorations.
2248 } else if (qualifier.hasLocation()) // inheritance
2249 location = qualifier.layoutLocation + locationOffset;
2250 }
John Kessenich6090df02016-06-30 21:18:02 -06002251 if (location >= 0)
2252 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2253
John Kessenich2f47bc92016-06-30 21:47:35 -06002254 if (qualifier.hasLocation()) // track for upcoming inheritance
2255 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2256
John Kessenich6090df02016-06-30 21:18:02 -06002257 // component, XFB, others
2258 if (glslangMember.getQualifier().hasComponent())
2259 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2260 if (glslangMember.getQualifier().hasXfbOffset())
2261 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2262 else if (explicitLayout != glslang::ElpNone) {
2263 // figure out what to do with offset, which is accumulating
2264 int nextOffset;
2265 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2266 if (offset >= 0)
2267 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2268 offset = nextOffset;
2269 }
2270
2271 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2272 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2273
2274 // built-in variable decorations
2275 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002276 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002277 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2278 }
2279 }
2280
2281 // Decorate the structure
2282 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2283 addDecoration(spvType, TranslateBlockDecoration(type));
2284 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2285 builder.addCapability(spv::CapabilityGeometryStreams);
2286 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2287 }
2288 if (glslangIntermediate->getXfbMode()) {
2289 builder.addCapability(spv::CapabilityTransformFeedback);
2290 if (type.getQualifier().hasXfbStride())
2291 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2292 if (type.getQualifier().hasXfbBuffer())
2293 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2294 }
2295}
2296
John Kessenich6c292d32016-02-15 20:58:50 -07002297// Turn the expression forming the array size into an id.
2298// This is not quite trivial, because of specialization constants.
2299// Sometimes, a raw constant is turned into an Id, and sometimes
2300// a specialization constant expression is.
2301spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2302{
2303 // First, see if this is sized with a node, meaning a specialization constant:
2304 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2305 if (specNode != nullptr) {
2306 builder.clearAccessChain();
2307 specNode->traverse(this);
2308 return accessChainLoad(specNode->getAsTyped()->getType());
2309 }
qining25262b32016-05-06 17:25:16 -04002310
John Kessenich6c292d32016-02-15 20:58:50 -07002311 // Otherwise, need a compile-time (front end) size, get it:
2312 int size = arraySizes.getDimSize(dim);
2313 assert(size > 0);
2314 return builder.makeUintConstant(size);
2315}
2316
John Kessenich103bef92016-02-08 21:38:15 -07002317// Wrap the builder's accessChainLoad to:
2318// - localize handling of RelaxedPrecision
2319// - use the SPIR-V inferred type instead of another conversion of the glslang type
2320// (avoids unnecessary work and possible type punning for structures)
2321// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002322spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2323{
John Kessenich103bef92016-02-08 21:38:15 -07002324 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2325 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2326
2327 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002328 if (type.getBasicType() == glslang::EbtBool) {
2329 if (builder.isScalarType(nominalTypeId)) {
2330 // Conversion for bool
2331 spv::Id boolType = builder.makeBoolType();
2332 if (nominalTypeId != boolType)
2333 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2334 } else if (builder.isVectorType(nominalTypeId)) {
2335 // Conversion for bvec
2336 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2337 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2338 if (nominalTypeId != bvecType)
2339 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2340 }
2341 }
John Kessenich103bef92016-02-08 21:38:15 -07002342
2343 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002344}
2345
Rex Xu27253232016-02-23 17:51:09 +08002346// Wrap the builder's accessChainStore to:
2347// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002348//
2349// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002350void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2351{
2352 // Need to convert to abstract types when necessary
2353 if (type.getBasicType() == glslang::EbtBool) {
2354 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2355
2356 if (builder.isScalarType(nominalTypeId)) {
2357 // Conversion for bool
2358 spv::Id boolType = builder.makeBoolType();
2359 if (nominalTypeId != boolType) {
2360 spv::Id zero = builder.makeUintConstant(0);
2361 spv::Id one = builder.makeUintConstant(1);
2362 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2363 }
2364 } else if (builder.isVectorType(nominalTypeId)) {
2365 // Conversion for bvec
2366 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2367 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2368 if (nominalTypeId != bvecType) {
2369 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2370 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2371 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2372 }
2373 }
2374 }
2375
2376 builder.accessChainStore(rvalue);
2377}
2378
John Kessenich4bf71552016-09-02 11:20:21 -06002379// For storing when types match at the glslang level, but not might match at the
2380// SPIR-V level.
2381//
2382// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002383// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002384// as in a member-decorated way.
2385//
2386// NOTE: This function can handle any store request; if it's not special it
2387// simplifies to a simple OpStore.
2388//
2389// Implicitly uses the existing builder.accessChain as the storage target.
2390void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2391{
John Kessenichb3e24e42016-09-11 12:33:43 -06002392 // we only do the complex path here if it's an aggregate
2393 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002394 accessChainStore(type, rValue);
2395 return;
2396 }
2397
John Kessenichb3e24e42016-09-11 12:33:43 -06002398 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002399 spv::Id rType = builder.getTypeId(rValue);
2400 spv::Id lValue = builder.accessChainGetLValue();
2401 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2402 if (lType == rType) {
2403 accessChainStore(type, rValue);
2404 return;
2405 }
2406
John Kessenichb3e24e42016-09-11 12:33:43 -06002407 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002408 // where the two types were the same type in GLSL. This requires member
2409 // by member copy, recursively.
2410
John Kessenichb3e24e42016-09-11 12:33:43 -06002411 // If an array, copy element by element.
2412 if (type.isArray()) {
2413 glslang::TType glslangElementType(type, 0);
2414 spv::Id elementRType = builder.getContainedTypeId(rType);
2415 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2416 // get the source member
2417 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002418
John Kessenichb3e24e42016-09-11 12:33:43 -06002419 // set up the target storage
2420 builder.clearAccessChain();
2421 builder.setAccessChainLValue(lValue);
2422 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002423
John Kessenichb3e24e42016-09-11 12:33:43 -06002424 // store the member
2425 multiTypeStore(glslangElementType, elementRValue);
2426 }
2427 } else {
2428 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002429
John Kessenichb3e24e42016-09-11 12:33:43 -06002430 // loop over structure members
2431 const glslang::TTypeList& members = *type.getStruct();
2432 for (int m = 0; m < (int)members.size(); ++m) {
2433 const glslang::TType& glslangMemberType = *members[m].type;
2434
2435 // get the source member
2436 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2437 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2438
2439 // set up the target storage
2440 builder.clearAccessChain();
2441 builder.setAccessChainLValue(lValue);
2442 builder.accessChainPush(builder.makeIntConstant(m));
2443
2444 // store the member
2445 multiTypeStore(glslangMemberType, memberRValue);
2446 }
John Kessenich4bf71552016-09-02 11:20:21 -06002447 }
2448}
2449
John Kessenichf85e8062015-12-19 13:57:10 -07002450// Decide whether or not this type should be
2451// decorated with offsets and strides, and if so
2452// whether std140 or std430 rules should be applied.
2453glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002454{
John Kessenichf85e8062015-12-19 13:57:10 -07002455 // has to be a block
2456 if (type.getBasicType() != glslang::EbtBlock)
2457 return glslang::ElpNone;
2458
2459 // has to be a uniform or buffer block
2460 if (type.getQualifier().storage != glslang::EvqUniform &&
2461 type.getQualifier().storage != glslang::EvqBuffer)
2462 return glslang::ElpNone;
2463
2464 // return the layout to use
2465 switch (type.getQualifier().layoutPacking) {
2466 case glslang::ElpStd140:
2467 case glslang::ElpStd430:
2468 return type.getQualifier().layoutPacking;
2469 default:
2470 return glslang::ElpNone;
2471 }
John Kessenich31ed4832015-09-09 17:51:38 -06002472}
2473
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002474// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002475int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002476{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002477 int size;
John Kessenich49987892015-12-29 17:11:44 -07002478 int stride;
2479 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002480
2481 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002482}
2483
John Kessenich49987892015-12-29 17:11:44 -07002484// 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 -07002485// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002486int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002487{
John Kessenich49987892015-12-29 17:11:44 -07002488 glslang::TType elementType;
2489 elementType.shallowCopy(matrixType);
2490 elementType.clearArraySizes();
2491
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002492 int size;
John Kessenich49987892015-12-29 17:11:44 -07002493 int stride;
2494 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2495
2496 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002497}
2498
John Kessenich5e4b1242015-08-06 22:53:06 -06002499// Given a member type of a struct, realign the current offset for it, and compute
2500// the next (not yet aligned) offset for the next member, which will get aligned
2501// on the next call.
2502// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2503// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2504// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002505void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002506 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002507{
2508 // this will get a positive value when deemed necessary
2509 nextOffset = -1;
2510
John Kessenich5e4b1242015-08-06 22:53:06 -06002511 // override anything in currentOffset with user-set offset
2512 if (memberType.getQualifier().hasOffset())
2513 currentOffset = memberType.getQualifier().layoutOffset;
2514
2515 // It could be that current linker usage in glslang updated all the layoutOffset,
2516 // in which case the following code does not matter. But, that's not quite right
2517 // once cross-compilation unit GLSL validation is done, as the original user
2518 // settings are needed in layoutOffset, and then the following will come into play.
2519
John Kessenichf85e8062015-12-19 13:57:10 -07002520 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002521 if (! memberType.getQualifier().hasOffset())
2522 currentOffset = -1;
2523
2524 return;
2525 }
2526
John Kessenichf85e8062015-12-19 13:57:10 -07002527 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002528 if (currentOffset < 0)
2529 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002530
John Kessenich5e4b1242015-08-06 22:53:06 -06002531 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2532 // but possibly not yet correctly aligned.
2533
2534 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002535 int dummyStride;
2536 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002537 glslang::RoundToPow2(currentOffset, memberAlignment);
2538 nextOffset = currentOffset + memberSize;
2539}
2540
David Netoa901ffe2016-06-08 14:11:40 +01002541void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002542{
David Netoa901ffe2016-06-08 14:11:40 +01002543 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2544 switch (glslangBuiltIn)
2545 {
2546 case glslang::EbvClipDistance:
2547 case glslang::EbvCullDistance:
2548 case glslang::EbvPointSize:
2549 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2550 // Alternately, we could just call this for any glslang built-in, since the
2551 // capability already guards against duplicates.
2552 TranslateBuiltInDecoration(glslangBuiltIn, false);
2553 break;
2554 default:
2555 // Capabilities were already generated when the struct was declared.
2556 break;
2557 }
John Kessenichebb50532016-05-16 19:22:05 -06002558}
2559
John Kessenich6fccb3c2016-09-19 16:01:41 -06002560bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002561{
John Kessenicheee9d532016-09-19 18:09:30 -06002562 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002563}
2564
2565// Make all the functions, skeletally, without actually visiting their bodies.
2566void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2567{
2568 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2569 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002570 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002571 continue;
2572
2573 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002574 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002575 //
qining25262b32016-05-06 17:25:16 -04002576 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002577 // function. What it is an address of varies:
2578 //
John Kessenich4bf71552016-09-02 11:20:21 -06002579 // - "in" parameters not marked as "const" can be written to without modifying the calling
2580 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002581 //
2582 // - "const in" parameters can just be the r-value, as no writes need occur.
2583 //
John Kessenich4bf71552016-09-02 11:20:21 -06002584 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2585 // 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 -06002586
2587 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002588 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2590
2591 for (int p = 0; p < (int)parameters.size(); ++p) {
2592 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2593 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002594 if (paramType.isOpaque())
2595 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2596 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002597 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2598 else
John Kessenich4bf71552016-09-02 11:20:21 -06002599 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002600 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002601 paramTypes.push_back(typeId);
2602 }
2603
2604 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002605 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2606 convertGlslangToSpvType(glslFunction->getType()),
2607 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002608
2609 // Track function to emit/call later
2610 functionMap[glslFunction->getName().c_str()] = function;
2611
2612 // Set the parameter id's
2613 for (int p = 0; p < (int)parameters.size(); ++p) {
2614 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2615 // give a name too
2616 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2617 }
2618 }
2619}
2620
2621// Process all the initializers, while skipping the functions and link objects
2622void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2623{
2624 builder.setBuildPoint(shaderEntry->getLastBlock());
2625 for (int i = 0; i < (int)initializers.size(); ++i) {
2626 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2627 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2628
2629 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002630 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002631 initializer->traverse(this);
2632 }
2633 }
2634}
2635
2636// Process all the functions, while skipping initializers.
2637void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2638{
2639 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2640 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002641 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002642 node->traverse(this);
2643 }
2644}
2645
2646void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2647{
qining25262b32016-05-06 17:25:16 -04002648 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002649 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002650 currentFunction = functionMap[node->getName().c_str()];
2651 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002652 builder.setBuildPoint(functionBlock);
2653}
2654
Rex Xu04db3f52015-09-16 11:44:02 +08002655void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002656{
Rex Xufc618912015-09-09 16:42:49 +08002657 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002658
2659 glslang::TSampler sampler = {};
2660 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002661 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002662 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2663 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2664 }
2665
John Kessenich140f3df2015-06-26 16:58:36 -06002666 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2667 builder.clearAccessChain();
2668 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002669
2670 // Special case l-value operands
2671 bool lvalue = false;
2672 switch (node.getOp()) {
2673 case glslang::EOpImageAtomicAdd:
2674 case glslang::EOpImageAtomicMin:
2675 case glslang::EOpImageAtomicMax:
2676 case glslang::EOpImageAtomicAnd:
2677 case glslang::EOpImageAtomicOr:
2678 case glslang::EOpImageAtomicXor:
2679 case glslang::EOpImageAtomicExchange:
2680 case glslang::EOpImageAtomicCompSwap:
2681 if (i == 0)
2682 lvalue = true;
2683 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002684 case glslang::EOpSparseImageLoad:
2685 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2686 lvalue = true;
2687 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002688 case glslang::EOpSparseTexture:
2689 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2690 lvalue = true;
2691 break;
2692 case glslang::EOpSparseTextureClamp:
2693 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2694 lvalue = true;
2695 break;
2696 case glslang::EOpSparseTextureLod:
2697 case glslang::EOpSparseTextureOffset:
2698 if (i == 3)
2699 lvalue = true;
2700 break;
2701 case glslang::EOpSparseTextureFetch:
2702 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2703 lvalue = true;
2704 break;
2705 case glslang::EOpSparseTextureFetchOffset:
2706 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2707 lvalue = true;
2708 break;
2709 case glslang::EOpSparseTextureLodOffset:
2710 case glslang::EOpSparseTextureGrad:
2711 case glslang::EOpSparseTextureOffsetClamp:
2712 if (i == 4)
2713 lvalue = true;
2714 break;
2715 case glslang::EOpSparseTextureGradOffset:
2716 case glslang::EOpSparseTextureGradClamp:
2717 if (i == 5)
2718 lvalue = true;
2719 break;
2720 case glslang::EOpSparseTextureGradOffsetClamp:
2721 if (i == 6)
2722 lvalue = true;
2723 break;
2724 case glslang::EOpSparseTextureGather:
2725 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2726 lvalue = true;
2727 break;
2728 case glslang::EOpSparseTextureGatherOffset:
2729 case glslang::EOpSparseTextureGatherOffsets:
2730 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2731 lvalue = true;
2732 break;
Rex Xufc618912015-09-09 16:42:49 +08002733 default:
2734 break;
2735 }
2736
Rex Xu6b86d492015-09-16 17:48:22 +08002737 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002738 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002739 else
John Kessenich32cfd492016-02-02 12:37:46 -07002740 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002741 }
2742}
2743
John Kessenichfc51d282015-08-19 13:34:18 -06002744void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002745{
John Kessenichfc51d282015-08-19 13:34:18 -06002746 builder.clearAccessChain();
2747 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002748 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002749}
John Kessenich140f3df2015-06-26 16:58:36 -06002750
John Kessenichfc51d282015-08-19 13:34:18 -06002751spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2752{
Rex Xufc618912015-09-09 16:42:49 +08002753 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002754 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002755 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002756 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002757
John Kessenichfc51d282015-08-19 13:34:18 -06002758 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002759 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2760 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2761 std::vector<spv::Id> arguments;
2762 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002763 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002764 else
2765 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002766 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002767
2768 spv::Builder::TextureParameters params = { };
2769 params.sampler = arguments[0];
2770
Rex Xu04db3f52015-09-16 11:44:02 +08002771 glslang::TCrackedTextureOp cracked;
2772 node->crackTexture(sampler, cracked);
2773
John Kessenichfc51d282015-08-19 13:34:18 -06002774 // Check for queries
2775 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002776 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2777 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002778 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002779
John Kessenichfc51d282015-08-19 13:34:18 -06002780 switch (node->getOp()) {
2781 case glslang::EOpImageQuerySize:
2782 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002783 if (arguments.size() > 1) {
2784 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002786 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002788 case glslang::EOpImageQuerySamples:
2789 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002791 case glslang::EOpTextureQueryLod:
2792 params.coords = arguments[1];
2793 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2794 case glslang::EOpTextureQueryLevels:
2795 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002796 case glslang::EOpSparseTexelsResident:
2797 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002798 default:
2799 assert(0);
2800 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002801 }
John Kessenich140f3df2015-06-26 16:58:36 -06002802 }
2803
Rex Xufc618912015-09-09 16:42:49 +08002804 // Check for image functions other than queries
2805 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002806 std::vector<spv::Id> operands;
2807 auto opIt = arguments.begin();
2808 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002809
2810 // Handle subpass operations
2811 // TODO: GLSL should change to have the "MS" only on the type rather than the
2812 // built-in function.
2813 if (cracked.subpass) {
2814 // add on the (0,0) coordinate
2815 spv::Id zero = builder.makeIntConstant(0);
2816 std::vector<spv::Id> comps;
2817 comps.push_back(zero);
2818 comps.push_back(zero);
2819 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2820 if (sampler.ms) {
2821 operands.push_back(spv::ImageOperandsSampleMask);
2822 operands.push_back(*(opIt++));
2823 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002824 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002825 }
2826
John Kessenich56bab042015-09-16 10:54:31 -06002827 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002828 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002829 if (sampler.ms) {
2830 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002831 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002832 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002833 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2834 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002835 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002836 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002837 if (sampler.ms) {
2838 operands.push_back(*(opIt + 1));
2839 operands.push_back(spv::ImageOperandsSampleMask);
2840 operands.push_back(*opIt);
2841 } else
2842 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002843 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002844 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2845 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002846 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002847 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2848 builder.addCapability(spv::CapabilitySparseResidency);
2849 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2850 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2851
2852 if (sampler.ms) {
2853 operands.push_back(spv::ImageOperandsSampleMask);
2854 operands.push_back(*opIt++);
2855 }
2856
2857 // Create the return type that was a special structure
2858 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002859 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002860 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2861 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2862
2863 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2864
2865 // Decode the return type
2866 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2867 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002868 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002869 // Process image atomic operations
2870
2871 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2872 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002873 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002874
John Kessenich8c8505c2016-07-26 12:50:38 -06002875 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002876 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002877
2878 std::vector<spv::Id> operands;
2879 operands.push_back(pointer);
2880 for (; opIt != arguments.end(); ++opIt)
2881 operands.push_back(*opIt);
2882
John Kessenich8c8505c2016-07-26 12:50:38 -06002883 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002884 }
2885 }
2886
2887 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002888 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002889 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2890
John Kessenichfc51d282015-08-19 13:34:18 -06002891 // check for bias argument
2892 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002893 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002894 int nonBiasArgCount = 2;
2895 if (cracked.offset)
2896 ++nonBiasArgCount;
2897 if (cracked.grad)
2898 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002899 if (cracked.lodClamp)
2900 ++nonBiasArgCount;
2901 if (sparse)
2902 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002903
2904 if ((int)arguments.size() > nonBiasArgCount)
2905 bias = true;
2906 }
2907
John Kessenicha5c33d62016-06-02 23:45:21 -06002908 // See if the sampler param should really be just the SPV image part
2909 if (cracked.fetch) {
2910 // a fetch needs to have the image extracted first
2911 if (builder.isSampledImage(params.sampler))
2912 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2913 }
2914
John Kessenichfc51d282015-08-19 13:34:18 -06002915 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002916
John Kessenichfc51d282015-08-19 13:34:18 -06002917 params.coords = arguments[1];
2918 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002919 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002920
2921 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002922 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002923 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002924 ++extraArgs;
2925 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002926 params.Dref = arguments[2];
2927 ++extraArgs;
2928 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002929 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002930 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002931 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002932 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002933 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002934 dRefComp = builder.getNumComponents(params.coords) - 1;
2935 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002936 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2937 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002938
2939 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002940 if (cracked.lod) {
2941 params.lod = arguments[2];
2942 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002943 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2944 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2945 noImplicitLod = true;
2946 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002947
2948 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002949 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002950 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002951 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002952 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002953
2954 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002955 if (cracked.grad) {
2956 params.gradX = arguments[2 + extraArgs];
2957 params.gradY = arguments[3 + extraArgs];
2958 extraArgs += 2;
2959 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002960
2961 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002962 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002963 params.offset = arguments[2 + extraArgs];
2964 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002965 } else if (cracked.offsets) {
2966 params.offsets = arguments[2 + extraArgs];
2967 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002968 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002969
2970 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002971 if (cracked.lodClamp) {
2972 params.lodClamp = arguments[2 + extraArgs];
2973 ++extraArgs;
2974 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002975
2976 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002977 if (sparse) {
2978 params.texelOut = arguments[2 + extraArgs];
2979 ++extraArgs;
2980 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002981
2982 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002983 if (bias) {
2984 params.bias = arguments[2 + extraArgs];
2985 ++extraArgs;
2986 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002987
2988 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002989 if (cracked.gather && ! sampler.shadow) {
2990 // default component is 0, if missing, otherwise an argument
2991 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002992 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002993 ++extraArgs;
2994 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002995 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002996 }
2997 }
John Kessenichfc51d282015-08-19 13:34:18 -06002998
John Kessenich65336482016-06-16 14:06:26 -06002999 // projective component (might not to move)
3000 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3001 // are divided by the last component of P."
3002 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3003 // unused components will appear after all used components."
3004 if (cracked.proj) {
3005 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3006 int projTargetComp;
3007 switch (sampler.dim) {
3008 case glslang::Esd1D: projTargetComp = 1; break;
3009 case glslang::Esd2D: projTargetComp = 2; break;
3010 case glslang::EsdRect: projTargetComp = 2; break;
3011 default: projTargetComp = projSourceComp; break;
3012 }
3013 // copy the projective coordinate if we have to
3014 if (projTargetComp != projSourceComp) {
3015 spv::Id projComp = builder.createCompositeExtract(params.coords,
3016 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3017 projSourceComp);
3018 params.coords = builder.createCompositeInsert(projComp, params.coords,
3019 builder.getTypeId(params.coords), projTargetComp);
3020 }
3021 }
3022
John Kessenich8c8505c2016-07-26 12:50:38 -06003023 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003024}
3025
3026spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3027{
3028 // Grab the function's pointer from the previously created function
3029 spv::Function* function = functionMap[node->getName().c_str()];
3030 if (! function)
3031 return 0;
3032
3033 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3034 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3035
3036 // See comments in makeFunctions() for details about the semantics for parameter passing.
3037 //
3038 // These imply we need a four step process:
3039 // 1. Evaluate the arguments
3040 // 2. Allocate and make copies of in, out, and inout arguments
3041 // 3. Make the call
3042 // 4. Copy back the results
3043
3044 // 1. Evaluate the arguments
3045 std::vector<spv::Builder::AccessChain> lValues;
3046 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003047 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003049 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003050 // build l-value
3051 builder.clearAccessChain();
3052 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003053 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003054 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003055 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003056 // save l-value
3057 lValues.push_back(builder.getAccessChain());
3058 } else {
3059 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003060 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003061 }
3062 }
3063
3064 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3065 // copy the original into that space.
3066 //
3067 // Also, build up the list of actual arguments to pass in for the call
3068 int lValueCount = 0;
3069 int rValueCount = 0;
3070 std::vector<spv::Id> spvArgs;
3071 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003072 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003073 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003074 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003075 builder.setAccessChain(lValues[lValueCount]);
3076 arg = builder.accessChainGetLValue();
3077 ++lValueCount;
3078 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003079 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003080 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3081 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3082 // need to copy the input into output space
3083 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003084 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003085 builder.clearAccessChain();
3086 builder.setAccessChainLValue(arg);
3087 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003088 }
3089 ++lValueCount;
3090 } else {
3091 arg = rValues[rValueCount];
3092 ++rValueCount;
3093 }
3094 spvArgs.push_back(arg);
3095 }
3096
3097 // 3. Make the call.
3098 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003099 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003100
3101 // 4. Copy back out an "out" arguments.
3102 lValueCount = 0;
3103 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003104 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003105 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3106 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3107 spv::Id copy = builder.createLoad(spvArgs[a]);
3108 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003109 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003110 }
3111 ++lValueCount;
3112 }
3113 }
3114
3115 return result;
3116}
3117
3118// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003119spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3120 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003121 spv::Id typeId, spv::Id left, spv::Id right,
3122 glslang::TBasicType typeProxy, bool reduceComparison)
3123{
Rex Xu8ff43de2016-04-22 16:51:45 +08003124 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003125#ifdef AMD_EXTENSIONS
3126 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3127#else
John Kessenich140f3df2015-06-26 16:58:36 -06003128 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003129#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003130 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003131
3132 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003133 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003134 bool comparison = false;
3135
3136 switch (op) {
3137 case glslang::EOpAdd:
3138 case glslang::EOpAddAssign:
3139 if (isFloat)
3140 binOp = spv::OpFAdd;
3141 else
3142 binOp = spv::OpIAdd;
3143 break;
3144 case glslang::EOpSub:
3145 case glslang::EOpSubAssign:
3146 if (isFloat)
3147 binOp = spv::OpFSub;
3148 else
3149 binOp = spv::OpISub;
3150 break;
3151 case glslang::EOpMul:
3152 case glslang::EOpMulAssign:
3153 if (isFloat)
3154 binOp = spv::OpFMul;
3155 else
3156 binOp = spv::OpIMul;
3157 break;
3158 case glslang::EOpVectorTimesScalar:
3159 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003160 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003161 if (builder.isVector(right))
3162 std::swap(left, right);
3163 assert(builder.isScalar(right));
3164 needMatchingVectors = false;
3165 binOp = spv::OpVectorTimesScalar;
3166 } else
3167 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003168 break;
3169 case glslang::EOpVectorTimesMatrix:
3170 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003171 binOp = spv::OpVectorTimesMatrix;
3172 break;
3173 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003174 binOp = spv::OpMatrixTimesVector;
3175 break;
3176 case glslang::EOpMatrixTimesScalar:
3177 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003178 binOp = spv::OpMatrixTimesScalar;
3179 break;
3180 case glslang::EOpMatrixTimesMatrix:
3181 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003182 binOp = spv::OpMatrixTimesMatrix;
3183 break;
3184 case glslang::EOpOuterProduct:
3185 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003186 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 break;
3188
3189 case glslang::EOpDiv:
3190 case glslang::EOpDivAssign:
3191 if (isFloat)
3192 binOp = spv::OpFDiv;
3193 else if (isUnsigned)
3194 binOp = spv::OpUDiv;
3195 else
3196 binOp = spv::OpSDiv;
3197 break;
3198 case glslang::EOpMod:
3199 case glslang::EOpModAssign:
3200 if (isFloat)
3201 binOp = spv::OpFMod;
3202 else if (isUnsigned)
3203 binOp = spv::OpUMod;
3204 else
3205 binOp = spv::OpSMod;
3206 break;
3207 case glslang::EOpRightShift:
3208 case glslang::EOpRightShiftAssign:
3209 if (isUnsigned)
3210 binOp = spv::OpShiftRightLogical;
3211 else
3212 binOp = spv::OpShiftRightArithmetic;
3213 break;
3214 case glslang::EOpLeftShift:
3215 case glslang::EOpLeftShiftAssign:
3216 binOp = spv::OpShiftLeftLogical;
3217 break;
3218 case glslang::EOpAnd:
3219 case glslang::EOpAndAssign:
3220 binOp = spv::OpBitwiseAnd;
3221 break;
3222 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003223 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003224 binOp = spv::OpLogicalAnd;
3225 break;
3226 case glslang::EOpInclusiveOr:
3227 case glslang::EOpInclusiveOrAssign:
3228 binOp = spv::OpBitwiseOr;
3229 break;
3230 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003231 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 binOp = spv::OpLogicalOr;
3233 break;
3234 case glslang::EOpExclusiveOr:
3235 case glslang::EOpExclusiveOrAssign:
3236 binOp = spv::OpBitwiseXor;
3237 break;
3238 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003239 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003240 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242
3243 case glslang::EOpLessThan:
3244 case glslang::EOpGreaterThan:
3245 case glslang::EOpLessThanEqual:
3246 case glslang::EOpGreaterThanEqual:
3247 case glslang::EOpEqual:
3248 case glslang::EOpNotEqual:
3249 case glslang::EOpVectorEqual:
3250 case glslang::EOpVectorNotEqual:
3251 comparison = true;
3252 break;
3253 default:
3254 break;
3255 }
3256
John Kessenich7c1aa102015-10-15 13:29:11 -06003257 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003258 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003259 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003260 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003261 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003262
3263 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003264 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003265 builder.promoteScalar(precision, left, right);
3266
qining25262b32016-05-06 17:25:16 -04003267 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3268 addDecoration(result, noContraction);
3269 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003270 }
3271
3272 if (! comparison)
3273 return 0;
3274
John Kessenich7c1aa102015-10-15 13:29:11 -06003275 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003276
John Kessenich4583b612016-08-07 19:14:22 -06003277 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3278 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003279 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003280
3281 switch (op) {
3282 case glslang::EOpLessThan:
3283 if (isFloat)
3284 binOp = spv::OpFOrdLessThan;
3285 else if (isUnsigned)
3286 binOp = spv::OpULessThan;
3287 else
3288 binOp = spv::OpSLessThan;
3289 break;
3290 case glslang::EOpGreaterThan:
3291 if (isFloat)
3292 binOp = spv::OpFOrdGreaterThan;
3293 else if (isUnsigned)
3294 binOp = spv::OpUGreaterThan;
3295 else
3296 binOp = spv::OpSGreaterThan;
3297 break;
3298 case glslang::EOpLessThanEqual:
3299 if (isFloat)
3300 binOp = spv::OpFOrdLessThanEqual;
3301 else if (isUnsigned)
3302 binOp = spv::OpULessThanEqual;
3303 else
3304 binOp = spv::OpSLessThanEqual;
3305 break;
3306 case glslang::EOpGreaterThanEqual:
3307 if (isFloat)
3308 binOp = spv::OpFOrdGreaterThanEqual;
3309 else if (isUnsigned)
3310 binOp = spv::OpUGreaterThanEqual;
3311 else
3312 binOp = spv::OpSGreaterThanEqual;
3313 break;
3314 case glslang::EOpEqual:
3315 case glslang::EOpVectorEqual:
3316 if (isFloat)
3317 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003318 else if (isBool)
3319 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 else
3321 binOp = spv::OpIEqual;
3322 break;
3323 case glslang::EOpNotEqual:
3324 case glslang::EOpVectorNotEqual:
3325 if (isFloat)
3326 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003327 else if (isBool)
3328 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003329 else
3330 binOp = spv::OpINotEqual;
3331 break;
3332 default:
3333 break;
3334 }
3335
qining25262b32016-05-06 17:25:16 -04003336 if (binOp != spv::OpNop) {
3337 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3338 addDecoration(result, noContraction);
3339 return builder.setPrecision(result, precision);
3340 }
John Kessenich140f3df2015-06-26 16:58:36 -06003341
3342 return 0;
3343}
3344
John Kessenich04bb8a02015-12-12 12:28:14 -07003345//
3346// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3347// These can be any of:
3348//
3349// matrix * scalar
3350// scalar * matrix
3351// matrix * matrix linear algebraic
3352// matrix * vector
3353// vector * matrix
3354// matrix * matrix componentwise
3355// matrix op matrix op in {+, -, /}
3356// matrix op scalar op in {+, -, /}
3357// scalar op matrix op in {+, -, /}
3358//
qining25262b32016-05-06 17:25:16 -04003359spv::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 -07003360{
3361 bool firstClass = true;
3362
3363 // First, handle first-class matrix operations (* and matrix/scalar)
3364 switch (op) {
3365 case spv::OpFDiv:
3366 if (builder.isMatrix(left) && builder.isScalar(right)) {
3367 // turn matrix / scalar into a multiply...
3368 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3369 op = spv::OpMatrixTimesScalar;
3370 } else
3371 firstClass = false;
3372 break;
3373 case spv::OpMatrixTimesScalar:
3374 if (builder.isMatrix(right))
3375 std::swap(left, right);
3376 assert(builder.isScalar(right));
3377 break;
3378 case spv::OpVectorTimesMatrix:
3379 assert(builder.isVector(left));
3380 assert(builder.isMatrix(right));
3381 break;
3382 case spv::OpMatrixTimesVector:
3383 assert(builder.isMatrix(left));
3384 assert(builder.isVector(right));
3385 break;
3386 case spv::OpMatrixTimesMatrix:
3387 assert(builder.isMatrix(left));
3388 assert(builder.isMatrix(right));
3389 break;
3390 default:
3391 firstClass = false;
3392 break;
3393 }
3394
qining25262b32016-05-06 17:25:16 -04003395 if (firstClass) {
3396 spv::Id result = builder.createBinOp(op, typeId, left, right);
3397 addDecoration(result, noContraction);
3398 return builder.setPrecision(result, precision);
3399 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003400
LoopDawg592860c2016-06-09 08:57:35 -06003401 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003402 // The result type of all of them is the same type as the (a) matrix operand.
3403 // The algorithm is to:
3404 // - break the matrix(es) into vectors
3405 // - smear any scalar to a vector
3406 // - do vector operations
3407 // - make a matrix out the vector results
3408 switch (op) {
3409 case spv::OpFAdd:
3410 case spv::OpFSub:
3411 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003412 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003413 case spv::OpFMul:
3414 {
3415 // one time set up...
3416 bool leftMat = builder.isMatrix(left);
3417 bool rightMat = builder.isMatrix(right);
3418 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3419 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3420 spv::Id scalarType = builder.getScalarTypeId(typeId);
3421 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3422 std::vector<spv::Id> results;
3423 spv::Id smearVec = spv::NoResult;
3424 if (builder.isScalar(left))
3425 smearVec = builder.smearScalar(precision, left, vecType);
3426 else if (builder.isScalar(right))
3427 smearVec = builder.smearScalar(precision, right, vecType);
3428
3429 // do each vector op
3430 for (unsigned int c = 0; c < numCols; ++c) {
3431 std::vector<unsigned int> indexes;
3432 indexes.push_back(c);
3433 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3434 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003435 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3436 addDecoration(result, noContraction);
3437 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003438 }
3439
3440 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003441 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003442 }
3443 default:
3444 assert(0);
3445 return spv::NoResult;
3446 }
3447}
3448
qining25262b32016-05-06 17:25:16 -04003449spv::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 -06003450{
3451 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003452 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003453 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003454 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003455#ifdef AMD_EXTENSIONS
3456 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3457#else
Rex Xu04db3f52015-09-16 11:44:02 +08003458 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003459#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003460
3461 switch (op) {
3462 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003463 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003464 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003465 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003466 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003467 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003468 unaryOp = spv::OpSNegate;
3469 break;
3470
3471 case glslang::EOpLogicalNot:
3472 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 unaryOp = spv::OpLogicalNot;
3474 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003475 case glslang::EOpBitwiseNot:
3476 unaryOp = spv::OpNot;
3477 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003478
John Kessenich140f3df2015-06-26 16:58:36 -06003479 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003480 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003481 break;
3482 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003483 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003484 break;
3485 case glslang::EOpTranspose:
3486 unaryOp = spv::OpTranspose;
3487 break;
3488
3489 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003490 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003494 break;
3495 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003496 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003497 break;
3498 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003499 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003500 break;
3501 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003502 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 break;
3504 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003506 break;
3507 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003508 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003509 break;
3510 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 break;
3513
3514 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003515 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003516 break;
3517 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003518 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003519 break;
3520 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003521 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003522 break;
3523 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003524 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003525 break;
3526 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003527 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003528 break;
3529 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003530 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 break;
3532
3533 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003534 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003535 break;
3536 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003537 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003538 break;
3539
3540 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003541 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003542 break;
3543 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003544 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003545 break;
3546 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003547 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003548 break;
3549 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003550 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003551 break;
3552 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003553 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003554 break;
3555 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003556 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003557 break;
3558
3559 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003560 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
3562 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003563 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003564 break;
3565 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003566 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003567 break;
3568 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003569 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003570 break;
3571 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003572 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003573 break;
3574 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003575 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003576 break;
3577
3578 case glslang::EOpIsNan:
3579 unaryOp = spv::OpIsNan;
3580 break;
3581 case glslang::EOpIsInf:
3582 unaryOp = spv::OpIsInf;
3583 break;
LoopDawg592860c2016-06-09 08:57:35 -06003584 case glslang::EOpIsFinite:
3585 unaryOp = spv::OpIsFinite;
3586 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003587
Rex Xucbc426e2015-12-15 16:03:10 +08003588 case glslang::EOpFloatBitsToInt:
3589 case glslang::EOpFloatBitsToUint:
3590 case glslang::EOpIntBitsToFloat:
3591 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003592 case glslang::EOpDoubleBitsToInt64:
3593 case glslang::EOpDoubleBitsToUint64:
3594 case glslang::EOpInt64BitsToDouble:
3595 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003596 unaryOp = spv::OpBitcast;
3597 break;
3598
John Kessenich140f3df2015-06-26 16:58:36 -06003599 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003600 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003601 break;
3602 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003603 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003604 break;
3605 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003606 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003607 break;
3608 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003609 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003610 break;
3611 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003612 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003613 break;
3614 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003615 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003616 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003617 case glslang::EOpPackSnorm4x8:
3618 libCall = spv::GLSLstd450PackSnorm4x8;
3619 break;
3620 case glslang::EOpUnpackSnorm4x8:
3621 libCall = spv::GLSLstd450UnpackSnorm4x8;
3622 break;
3623 case glslang::EOpPackUnorm4x8:
3624 libCall = spv::GLSLstd450PackUnorm4x8;
3625 break;
3626 case glslang::EOpUnpackUnorm4x8:
3627 libCall = spv::GLSLstd450UnpackUnorm4x8;
3628 break;
3629 case glslang::EOpPackDouble2x32:
3630 libCall = spv::GLSLstd450PackDouble2x32;
3631 break;
3632 case glslang::EOpUnpackDouble2x32:
3633 libCall = spv::GLSLstd450UnpackDouble2x32;
3634 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003635
Rex Xu8ff43de2016-04-22 16:51:45 +08003636 case glslang::EOpPackInt2x32:
3637 case glslang::EOpUnpackInt2x32:
3638 case glslang::EOpPackUint2x32:
3639 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003640 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003641 break;
3642
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003643#ifdef AMD_EXTENSIONS
3644 case glslang::EOpPackFloat2x16:
3645 case glslang::EOpUnpackFloat2x16:
3646 unaryOp = spv::OpBitcast;
3647 break;
3648#endif
3649
John Kessenich140f3df2015-06-26 16:58:36 -06003650 case glslang::EOpDPdx:
3651 unaryOp = spv::OpDPdx;
3652 break;
3653 case glslang::EOpDPdy:
3654 unaryOp = spv::OpDPdy;
3655 break;
3656 case glslang::EOpFwidth:
3657 unaryOp = spv::OpFwidth;
3658 break;
3659 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003660 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003661 unaryOp = spv::OpDPdxFine;
3662 break;
3663 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003664 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003665 unaryOp = spv::OpDPdyFine;
3666 break;
3667 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003668 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003669 unaryOp = spv::OpFwidthFine;
3670 break;
3671 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003672 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003673 unaryOp = spv::OpDPdxCoarse;
3674 break;
3675 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003676 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003677 unaryOp = spv::OpDPdyCoarse;
3678 break;
3679 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003680 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003681 unaryOp = spv::OpFwidthCoarse;
3682 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003683 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003684 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003685 libCall = spv::GLSLstd450InterpolateAtCentroid;
3686 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 case glslang::EOpAny:
3688 unaryOp = spv::OpAny;
3689 break;
3690 case glslang::EOpAll:
3691 unaryOp = spv::OpAll;
3692 break;
3693
3694 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003695 if (isFloat)
3696 libCall = spv::GLSLstd450FAbs;
3697 else
3698 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003701 if (isFloat)
3702 libCall = spv::GLSLstd450FSign;
3703 else
3704 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003705 break;
3706
John Kessenichfc51d282015-08-19 13:34:18 -06003707 case glslang::EOpAtomicCounterIncrement:
3708 case glslang::EOpAtomicCounterDecrement:
3709 case glslang::EOpAtomicCounter:
3710 {
3711 // Handle all of the atomics in one place, in createAtomicOperation()
3712 std::vector<spv::Id> operands;
3713 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003714 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003715 }
3716
John Kessenichfc51d282015-08-19 13:34:18 -06003717 case glslang::EOpBitFieldReverse:
3718 unaryOp = spv::OpBitReverse;
3719 break;
3720 case glslang::EOpBitCount:
3721 unaryOp = spv::OpBitCount;
3722 break;
3723 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003724 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003725 break;
3726 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003727 if (isUnsigned)
3728 libCall = spv::GLSLstd450FindUMsb;
3729 else
3730 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003731 break;
3732
Rex Xu574ab042016-04-14 16:53:07 +08003733 case glslang::EOpBallot:
3734 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003735 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003736 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003737 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003738#ifdef AMD_EXTENSIONS
3739 case glslang::EOpMinInvocations:
3740 case glslang::EOpMaxInvocations:
3741 case glslang::EOpAddInvocations:
3742 case glslang::EOpMinInvocationsNonUniform:
3743 case glslang::EOpMaxInvocationsNonUniform:
3744 case glslang::EOpAddInvocationsNonUniform:
3745#endif
Rex Xu51596642016-09-21 18:56:12 +08003746 {
3747 std::vector<spv::Id> operands;
3748 operands.push_back(operand);
3749 return createInvocationsOperation(op, typeId, operands, typeProxy);
3750 }
Rex Xu9d93a232016-05-05 12:30:44 +08003751
3752#ifdef AMD_EXTENSIONS
3753 case glslang::EOpMbcnt:
3754 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3755 libCall = spv::MbcntAMD;
3756 break;
3757
3758 case glslang::EOpCubeFaceIndex:
3759 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3760 libCall = spv::CubeFaceIndexAMD;
3761 break;
3762
3763 case glslang::EOpCubeFaceCoord:
3764 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3765 libCall = spv::CubeFaceCoordAMD;
3766 break;
3767#endif
Rex Xu338b1852016-05-05 20:38:33 +08003768
John Kessenich140f3df2015-06-26 16:58:36 -06003769 default:
3770 return 0;
3771 }
3772
3773 spv::Id id;
3774 if (libCall >= 0) {
3775 std::vector<spv::Id> args;
3776 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003777 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003778 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003779 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003780 }
John Kessenich140f3df2015-06-26 16:58:36 -06003781
qining25262b32016-05-06 17:25:16 -04003782 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003783 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003784}
3785
John Kessenich7a53f762016-01-20 11:19:27 -07003786// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003787spv::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 -07003788{
3789 // Handle unary operations vector by vector.
3790 // The result type is the same type as the original type.
3791 // The algorithm is to:
3792 // - break the matrix into vectors
3793 // - apply the operation to each vector
3794 // - make a matrix out the vector results
3795
3796 // get the types sorted out
3797 int numCols = builder.getNumColumns(operand);
3798 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003799 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3800 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003801 std::vector<spv::Id> results;
3802
3803 // do each vector op
3804 for (int c = 0; c < numCols; ++c) {
3805 std::vector<unsigned int> indexes;
3806 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003807 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3808 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3809 addDecoration(destVec, noContraction);
3810 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003811 }
3812
3813 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003814 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003815}
3816
Rex Xu73e3ce72016-04-27 18:48:17 +08003817spv::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 -06003818{
3819 spv::Op convOp = spv::OpNop;
3820 spv::Id zero = 0;
3821 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003822 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003823
3824 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3825
3826 switch (op) {
3827 case glslang::EOpConvIntToBool:
3828 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003829 case glslang::EOpConvInt64ToBool:
3830 case glslang::EOpConvUint64ToBool:
3831 zero = (op == glslang::EOpConvInt64ToBool ||
3832 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003833 zero = makeSmearedConstant(zero, vectorSize);
3834 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3835
3836 case glslang::EOpConvFloatToBool:
3837 zero = builder.makeFloatConstant(0.0F);
3838 zero = makeSmearedConstant(zero, vectorSize);
3839 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3840
3841 case glslang::EOpConvDoubleToBool:
3842 zero = builder.makeDoubleConstant(0.0);
3843 zero = makeSmearedConstant(zero, vectorSize);
3844 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3845
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003846#ifdef AMD_EXTENSIONS
3847 case glslang::EOpConvFloat16ToBool:
3848 zero = builder.makeFloat16Constant(0.0F);
3849 zero = makeSmearedConstant(zero, vectorSize);
3850 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3851#endif
3852
John Kessenich140f3df2015-06-26 16:58:36 -06003853 case glslang::EOpConvBoolToFloat:
3854 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003855 zero = builder.makeFloatConstant(0.0F);
3856 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003857 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003858
John Kessenich140f3df2015-06-26 16:58:36 -06003859 case glslang::EOpConvBoolToDouble:
3860 convOp = spv::OpSelect;
3861 zero = builder.makeDoubleConstant(0.0);
3862 one = builder.makeDoubleConstant(1.0);
3863 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003864
3865#ifdef AMD_EXTENSIONS
3866 case glslang::EOpConvBoolToFloat16:
3867 convOp = spv::OpSelect;
3868 zero = builder.makeFloat16Constant(0.0F);
3869 one = builder.makeFloat16Constant(1.0F);
3870 break;
3871#endif
3872
John Kessenich140f3df2015-06-26 16:58:36 -06003873 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003874 case glslang::EOpConvBoolToInt64:
3875 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3876 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003877 convOp = spv::OpSelect;
3878 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003879
John Kessenich140f3df2015-06-26 16:58:36 -06003880 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003881 case glslang::EOpConvBoolToUint64:
3882 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3883 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003884 convOp = spv::OpSelect;
3885 break;
3886
3887 case glslang::EOpConvIntToFloat:
3888 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003889 case glslang::EOpConvInt64ToFloat:
3890 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003891#ifdef AMD_EXTENSIONS
3892 case glslang::EOpConvIntToFloat16:
3893 case glslang::EOpConvInt64ToFloat16:
3894#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003895 convOp = spv::OpConvertSToF;
3896 break;
3897
3898 case glslang::EOpConvUintToFloat:
3899 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003900 case glslang::EOpConvUint64ToFloat:
3901 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003902#ifdef AMD_EXTENSIONS
3903 case glslang::EOpConvUintToFloat16:
3904 case glslang::EOpConvUint64ToFloat16:
3905#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003906 convOp = spv::OpConvertUToF;
3907 break;
3908
3909 case glslang::EOpConvDoubleToFloat:
3910 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003911#ifdef AMD_EXTENSIONS
3912 case glslang::EOpConvDoubleToFloat16:
3913 case glslang::EOpConvFloat16ToDouble:
3914 case glslang::EOpConvFloatToFloat16:
3915 case glslang::EOpConvFloat16ToFloat:
3916#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003917 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003918 if (builder.isMatrixType(destType))
3919 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003920 break;
3921
3922 case glslang::EOpConvFloatToInt:
3923 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003924 case glslang::EOpConvFloatToInt64:
3925 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003926#ifdef AMD_EXTENSIONS
3927 case glslang::EOpConvFloat16ToInt:
3928 case glslang::EOpConvFloat16ToInt64:
3929#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003930 convOp = spv::OpConvertFToS;
3931 break;
3932
3933 case glslang::EOpConvUintToInt:
3934 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003935 case glslang::EOpConvUint64ToInt64:
3936 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003937 if (builder.isInSpecConstCodeGenMode()) {
3938 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003939 zero = (op == glslang::EOpConvUint64ToInt64 ||
3940 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003941 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003942 // Use OpIAdd, instead of OpBitcast to do the conversion when
3943 // generating for OpSpecConstantOp instruction.
3944 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3945 }
3946 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003947 convOp = spv::OpBitcast;
3948 break;
3949
3950 case glslang::EOpConvFloatToUint:
3951 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003952 case glslang::EOpConvFloatToUint64:
3953 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003954#ifdef AMD_EXTENSIONS
3955 case glslang::EOpConvFloat16ToUint:
3956 case glslang::EOpConvFloat16ToUint64:
3957#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003958 convOp = spv::OpConvertFToU;
3959 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003960
3961 case glslang::EOpConvIntToInt64:
3962 case glslang::EOpConvInt64ToInt:
3963 convOp = spv::OpSConvert;
3964 break;
3965
3966 case glslang::EOpConvUintToUint64:
3967 case glslang::EOpConvUint64ToUint:
3968 convOp = spv::OpUConvert;
3969 break;
3970
3971 case glslang::EOpConvIntToUint64:
3972 case glslang::EOpConvInt64ToUint:
3973 case glslang::EOpConvUint64ToInt:
3974 case glslang::EOpConvUintToInt64:
3975 // OpSConvert/OpUConvert + OpBitCast
3976 switch (op) {
3977 case glslang::EOpConvIntToUint64:
3978 convOp = spv::OpSConvert;
3979 type = builder.makeIntType(64);
3980 break;
3981 case glslang::EOpConvInt64ToUint:
3982 convOp = spv::OpSConvert;
3983 type = builder.makeIntType(32);
3984 break;
3985 case glslang::EOpConvUint64ToInt:
3986 convOp = spv::OpUConvert;
3987 type = builder.makeUintType(32);
3988 break;
3989 case glslang::EOpConvUintToInt64:
3990 convOp = spv::OpUConvert;
3991 type = builder.makeUintType(64);
3992 break;
3993 default:
3994 assert(0);
3995 break;
3996 }
3997
3998 if (vectorSize > 0)
3999 type = builder.makeVectorType(type, vectorSize);
4000
4001 operand = builder.createUnaryOp(convOp, type, operand);
4002
4003 if (builder.isInSpecConstCodeGenMode()) {
4004 // Build zero scalar or vector for OpIAdd.
4005 zero = (op == glslang::EOpConvIntToUint64 ||
4006 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4007 zero = makeSmearedConstant(zero, vectorSize);
4008 // Use OpIAdd, instead of OpBitcast to do the conversion when
4009 // generating for OpSpecConstantOp instruction.
4010 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4011 }
4012 // For normal run-time conversion instruction, use OpBitcast.
4013 convOp = spv::OpBitcast;
4014 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 default:
4016 break;
4017 }
4018
4019 spv::Id result = 0;
4020 if (convOp == spv::OpNop)
4021 return result;
4022
4023 if (convOp == spv::OpSelect) {
4024 zero = makeSmearedConstant(zero, vectorSize);
4025 one = makeSmearedConstant(one, vectorSize);
4026 result = builder.createTriOp(convOp, destType, operand, one, zero);
4027 } else
4028 result = builder.createUnaryOp(convOp, destType, operand);
4029
John Kessenich32cfd492016-02-02 12:37:46 -07004030 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004031}
4032
4033spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4034{
4035 if (vectorSize == 0)
4036 return constant;
4037
4038 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4039 std::vector<spv::Id> components;
4040 for (int c = 0; c < vectorSize; ++c)
4041 components.push_back(constant);
4042 return builder.makeCompositeConstant(vectorTypeId, components);
4043}
4044
John Kessenich426394d2015-07-23 10:22:48 -06004045// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004046spv::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 -06004047{
4048 spv::Op opCode = spv::OpNop;
4049
4050 switch (op) {
4051 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004052 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004053 opCode = spv::OpAtomicIAdd;
4054 break;
4055 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004056 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004057 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004058 break;
4059 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004060 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004061 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004062 break;
4063 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004064 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004065 opCode = spv::OpAtomicAnd;
4066 break;
4067 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004068 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004069 opCode = spv::OpAtomicOr;
4070 break;
4071 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004072 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004073 opCode = spv::OpAtomicXor;
4074 break;
4075 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004076 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004077 opCode = spv::OpAtomicExchange;
4078 break;
4079 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004080 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004081 opCode = spv::OpAtomicCompareExchange;
4082 break;
4083 case glslang::EOpAtomicCounterIncrement:
4084 opCode = spv::OpAtomicIIncrement;
4085 break;
4086 case glslang::EOpAtomicCounterDecrement:
4087 opCode = spv::OpAtomicIDecrement;
4088 break;
4089 case glslang::EOpAtomicCounter:
4090 opCode = spv::OpAtomicLoad;
4091 break;
4092 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004093 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004094 break;
4095 }
4096
4097 // Sort out the operands
4098 // - mapping from glslang -> SPV
4099 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004100 // - compare-exchange swaps the value and comparator
4101 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004102 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4103 auto opIt = operands.begin(); // walk the glslang operands
4104 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004105 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4106 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4107 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004108 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4109 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004110 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004111 spvAtomicOperands.push_back(*(opIt + 1));
4112 spvAtomicOperands.push_back(*opIt);
4113 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004114 }
John Kessenich426394d2015-07-23 10:22:48 -06004115
John Kessenich3e60a6f2015-09-14 22:45:16 -06004116 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004117 for (; opIt != operands.end(); ++opIt)
4118 spvAtomicOperands.push_back(*opIt);
4119
4120 return builder.createOp(opCode, typeId, spvAtomicOperands);
4121}
4122
John Kessenich91cef522016-05-05 16:45:40 -06004123// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004124spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004125{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004126#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004127 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004128 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004129#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004130
Rex Xu51596642016-09-21 18:56:12 +08004131 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004132
Rex Xu51596642016-09-21 18:56:12 +08004133 std::vector<spv::Id> spvGroupOperands;
4134 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4135 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4136 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4137 } else {
4138 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004139#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004140 if (op == glslang::EOpMinInvocationsNonUniform ||
4141 op == glslang::EOpMaxInvocationsNonUniform ||
4142 op == glslang::EOpAddInvocationsNonUniform)
4143 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004144#endif
Rex Xu51596642016-09-21 18:56:12 +08004145
4146 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004147#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004148 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4149 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4150 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004151#endif
Rex Xu51596642016-09-21 18:56:12 +08004152 }
4153
4154 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4155 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004156
4157 switch (op) {
4158 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004159 opCode = spv::OpGroupAny;
4160 break;
John Kessenich91cef522016-05-05 16:45:40 -06004161 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004162 opCode = spv::OpGroupAll;
4163 break;
John Kessenich91cef522016-05-05 16:45:40 -06004164 case glslang::EOpAllInvocationsEqual:
4165 {
Rex Xu51596642016-09-21 18:56:12 +08004166 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4167 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004168
4169 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4170 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4171 }
Rex Xu51596642016-09-21 18:56:12 +08004172
4173 case glslang::EOpReadInvocation:
4174 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004175 if (builder.isVectorType(typeId))
4176 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004177 break;
4178 case glslang::EOpReadFirstInvocation:
4179 opCode = spv::OpSubgroupFirstInvocationKHR;
4180 break;
4181 case glslang::EOpBallot:
4182 {
4183 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4184 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4185 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4186 //
4187 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4188 //
4189 spv::Id uintType = builder.makeUintType(32);
4190 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4191 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4192
4193 std::vector<spv::Id> components;
4194 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4195 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4196
4197 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4198 return builder.createUnaryOp(spv::OpBitcast, typeId,
4199 builder.createCompositeConstruct(uvec2Type, components));
4200 }
4201
Rex Xu9d93a232016-05-05 12:30:44 +08004202#ifdef AMD_EXTENSIONS
4203 case glslang::EOpMinInvocations:
4204 case glslang::EOpMaxInvocations:
4205 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004206 if (op == glslang::EOpMinInvocations) {
4207 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004208 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004209 else {
4210 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004211 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004212 else
Rex Xu51596642016-09-21 18:56:12 +08004213 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004214 }
4215 } else if (op == glslang::EOpMaxInvocations) {
4216 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004217 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004218 else {
4219 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004220 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004221 else
Rex Xu51596642016-09-21 18:56:12 +08004222 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004223 }
4224 } else {
4225 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004226 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004227 else
Rex Xu51596642016-09-21 18:56:12 +08004228 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004229 }
4230
Rex Xu2bbbe062016-08-23 15:41:05 +08004231 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004232 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004233
4234 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004235 case glslang::EOpMinInvocationsNonUniform:
4236 case glslang::EOpMaxInvocationsNonUniform:
4237 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004238 if (op == glslang::EOpMinInvocationsNonUniform) {
4239 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004240 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004241 else {
4242 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004243 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004244 else
Rex Xu51596642016-09-21 18:56:12 +08004245 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004246 }
4247 }
4248 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4249 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004250 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004251 else {
4252 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004253 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004254 else
Rex Xu51596642016-09-21 18:56:12 +08004255 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004256 }
4257 }
4258 else {
4259 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004260 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004261 else
Rex Xu51596642016-09-21 18:56:12 +08004262 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004263 }
4264
Rex Xu2bbbe062016-08-23 15:41:05 +08004265 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004266 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004267
4268 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004269#endif
John Kessenich91cef522016-05-05 16:45:40 -06004270 default:
4271 logger->missingFunctionality("invocation operation");
4272 return spv::NoResult;
4273 }
Rex Xu51596642016-09-21 18:56:12 +08004274
4275 assert(opCode != spv::OpNop);
4276 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004277}
4278
Rex Xu2bbbe062016-08-23 15:41:05 +08004279// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004280spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004281{
Rex Xub7072052016-09-26 15:53:40 +08004282#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004283 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4284 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004285 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
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 ||
4292 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4293#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004294
4295 // Handle group invocation operations scalar by scalar.
4296 // The result type is the same type as the original type.
4297 // The algorithm is to:
4298 // - break the vector into scalars
4299 // - apply the operation to each scalar
4300 // - make a vector out the scalar results
4301
4302 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004303 int numComponents = builder.getNumComponents(operands[0]);
4304 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004305 std::vector<spv::Id> results;
4306
4307 // do each scalar op
4308 for (int comp = 0; comp < numComponents; ++comp) {
4309 std::vector<unsigned int> indexes;
4310 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004311 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004312
Rex Xub7072052016-09-26 15:53:40 +08004313 std::vector<spv::Id> spvGroupOperands;
4314 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4315 if (op == spv::OpGroupBroadcast) {
4316 spvGroupOperands.push_back(scalar);
4317 spvGroupOperands.push_back(operands[1]);
4318 } else {
4319 spvGroupOperands.push_back(spv::GroupOperationReduce);
4320 spvGroupOperands.push_back(scalar);
4321 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004322
Rex Xub7072052016-09-26 15:53:40 +08004323 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004324 }
4325
4326 // put the pieces together
4327 return builder.createCompositeConstruct(typeId, results);
4328}
Rex Xu2bbbe062016-08-23 15:41:05 +08004329
John Kessenich5e4b1242015-08-06 22:53:06 -06004330spv::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 -06004331{
Rex Xu8ff43de2016-04-22 16:51:45 +08004332 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004333#ifdef AMD_EXTENSIONS
4334 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4335#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004336 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004337#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004338
John Kessenich140f3df2015-06-26 16:58:36 -06004339 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004340 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004341 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004342 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004343 spv::Id typeId0 = 0;
4344 if (consumedOperands > 0)
4345 typeId0 = builder.getTypeId(operands[0]);
4346 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004347
4348 switch (op) {
4349 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004350 if (isFloat)
4351 libCall = spv::GLSLstd450FMin;
4352 else if (isUnsigned)
4353 libCall = spv::GLSLstd450UMin;
4354 else
4355 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004356 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004357 break;
4358 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004359 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004360 break;
4361 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004362 if (isFloat)
4363 libCall = spv::GLSLstd450FMax;
4364 else if (isUnsigned)
4365 libCall = spv::GLSLstd450UMax;
4366 else
4367 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004368 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004369 break;
4370 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004371 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004372 break;
4373 case glslang::EOpDot:
4374 opCode = spv::OpDot;
4375 break;
4376 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004377 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004378 break;
4379
4380 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004381 if (isFloat)
4382 libCall = spv::GLSLstd450FClamp;
4383 else if (isUnsigned)
4384 libCall = spv::GLSLstd450UClamp;
4385 else
4386 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004387 builder.promoteScalar(precision, operands.front(), operands[1]);
4388 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004389 break;
4390 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004391 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4392 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004393 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004394 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004395 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004396 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004397 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004398 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004399 break;
4400 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004401 libCall = spv::GLSLstd450Step;
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::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004405 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004406 builder.promoteScalar(precision, operands[0], operands[2]);
4407 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004408 break;
4409
4410 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004411 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004412 break;
4413 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004414 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004415 break;
4416 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004417 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004418 break;
4419 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004420 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004421 break;
4422 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004423 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004424 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004425 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004426 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004427 libCall = spv::GLSLstd450InterpolateAtSample;
4428 break;
4429 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004430 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004431 libCall = spv::GLSLstd450InterpolateAtOffset;
4432 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004433 case glslang::EOpAddCarry:
4434 opCode = spv::OpIAddCarry;
4435 typeId = builder.makeStructResultType(typeId0, typeId0);
4436 consumedOperands = 2;
4437 break;
4438 case glslang::EOpSubBorrow:
4439 opCode = spv::OpISubBorrow;
4440 typeId = builder.makeStructResultType(typeId0, typeId0);
4441 consumedOperands = 2;
4442 break;
4443 case glslang::EOpUMulExtended:
4444 opCode = spv::OpUMulExtended;
4445 typeId = builder.makeStructResultType(typeId0, typeId0);
4446 consumedOperands = 2;
4447 break;
4448 case glslang::EOpIMulExtended:
4449 opCode = spv::OpSMulExtended;
4450 typeId = builder.makeStructResultType(typeId0, typeId0);
4451 consumedOperands = 2;
4452 break;
4453 case glslang::EOpBitfieldExtract:
4454 if (isUnsigned)
4455 opCode = spv::OpBitFieldUExtract;
4456 else
4457 opCode = spv::OpBitFieldSExtract;
4458 break;
4459 case glslang::EOpBitfieldInsert:
4460 opCode = spv::OpBitFieldInsert;
4461 break;
4462
4463 case glslang::EOpFma:
4464 libCall = spv::GLSLstd450Fma;
4465 break;
4466 case glslang::EOpFrexp:
4467 libCall = spv::GLSLstd450FrexpStruct;
4468 if (builder.getNumComponents(operands[0]) == 1)
4469 frexpIntType = builder.makeIntegerType(32, true);
4470 else
4471 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4472 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4473 consumedOperands = 1;
4474 break;
4475 case glslang::EOpLdexp:
4476 libCall = spv::GLSLstd450Ldexp;
4477 break;
4478
Rex Xu574ab042016-04-14 16:53:07 +08004479 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004480 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004481
Rex Xu9d93a232016-05-05 12:30:44 +08004482#ifdef AMD_EXTENSIONS
4483 case glslang::EOpSwizzleInvocations:
4484 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4485 libCall = spv::SwizzleInvocationsAMD;
4486 break;
4487 case glslang::EOpSwizzleInvocationsMasked:
4488 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4489 libCall = spv::SwizzleInvocationsMaskedAMD;
4490 break;
4491 case glslang::EOpWriteInvocation:
4492 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4493 libCall = spv::WriteInvocationAMD;
4494 break;
4495
4496 case glslang::EOpMin3:
4497 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4498 if (isFloat)
4499 libCall = spv::FMin3AMD;
4500 else {
4501 if (isUnsigned)
4502 libCall = spv::UMin3AMD;
4503 else
4504 libCall = spv::SMin3AMD;
4505 }
4506 break;
4507 case glslang::EOpMax3:
4508 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4509 if (isFloat)
4510 libCall = spv::FMax3AMD;
4511 else {
4512 if (isUnsigned)
4513 libCall = spv::UMax3AMD;
4514 else
4515 libCall = spv::SMax3AMD;
4516 }
4517 break;
4518 case glslang::EOpMid3:
4519 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4520 if (isFloat)
4521 libCall = spv::FMid3AMD;
4522 else {
4523 if (isUnsigned)
4524 libCall = spv::UMid3AMD;
4525 else
4526 libCall = spv::SMid3AMD;
4527 }
4528 break;
4529
4530 case glslang::EOpInterpolateAtVertex:
4531 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4532 libCall = spv::InterpolateAtVertexAMD;
4533 break;
4534#endif
4535
John Kessenich140f3df2015-06-26 16:58:36 -06004536 default:
4537 return 0;
4538 }
4539
4540 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004541 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004542 // Use an extended instruction from the standard library.
4543 // Construct the call arguments, without modifying the original operands vector.
4544 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4545 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004546 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004547 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004548 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004549 case 0:
4550 // should all be handled by visitAggregate and createNoArgOperation
4551 assert(0);
4552 return 0;
4553 case 1:
4554 // should all be handled by createUnaryOperation
4555 assert(0);
4556 return 0;
4557 case 2:
4558 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4559 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004560 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004561 // anything 3 or over doesn't have l-value operands, so all should be consumed
4562 assert(consumedOperands == operands.size());
4563 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004564 break;
4565 }
4566 }
4567
John Kessenich55e7d112015-11-15 21:33:39 -07004568 // Decode the return types that were structures
4569 switch (op) {
4570 case glslang::EOpAddCarry:
4571 case glslang::EOpSubBorrow:
4572 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4573 id = builder.createCompositeExtract(id, typeId0, 0);
4574 break;
4575 case glslang::EOpUMulExtended:
4576 case glslang::EOpIMulExtended:
4577 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4578 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4579 break;
4580 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004581 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004582 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4583 id = builder.createCompositeExtract(id, typeId0, 0);
4584 break;
4585 default:
4586 break;
4587 }
4588
John Kessenich32cfd492016-02-02 12:37:46 -07004589 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004590}
4591
Rex Xu9d93a232016-05-05 12:30:44 +08004592// Intrinsics with no arguments (or no return value, and no precision).
4593spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004594{
4595 // TODO: get the barrier operands correct
4596
4597 switch (op) {
4598 case glslang::EOpEmitVertex:
4599 builder.createNoResultOp(spv::OpEmitVertex);
4600 return 0;
4601 case glslang::EOpEndPrimitive:
4602 builder.createNoResultOp(spv::OpEndPrimitive);
4603 return 0;
4604 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004605 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004606 return 0;
4607 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004608 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004609 return 0;
4610 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004611 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004612 return 0;
4613 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004614 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004615 return 0;
4616 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004617 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004618 return 0;
4619 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004620 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004621 return 0;
4622 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004623 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004624 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004625 case glslang::EOpAllMemoryBarrierWithGroupSync:
4626 // Control barrier with non-"None" semantic is also a memory barrier.
4627 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4628 return 0;
4629 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4630 // Control barrier with non-"None" semantic is also a memory barrier.
4631 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4632 return 0;
4633 case glslang::EOpWorkgroupMemoryBarrier:
4634 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4635 return 0;
4636 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4637 // Control barrier with non-"None" semantic is also a memory barrier.
4638 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4639 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004640#ifdef AMD_EXTENSIONS
4641 case glslang::EOpTime:
4642 {
4643 std::vector<spv::Id> args; // Dummy arguments
4644 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4645 return builder.setPrecision(id, precision);
4646 }
4647#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004648 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004649 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004650 return 0;
4651 }
4652}
4653
4654spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4655{
John Kessenich2f273362015-07-18 22:34:27 -06004656 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004657 spv::Id id;
4658 if (symbolValues.end() != iter) {
4659 id = iter->second;
4660 return id;
4661 }
4662
4663 // it was not found, create it
4664 id = createSpvVariable(symbol);
4665 symbolValues[symbol->getId()] = id;
4666
Rex Xuc884b4a2016-06-29 15:03:44 +08004667 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004668 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004669 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004670 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004671 if (symbol->getType().getQualifier().hasSpecConstantId())
4672 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004673 if (symbol->getQualifier().hasIndex())
4674 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4675 if (symbol->getQualifier().hasComponent())
4676 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4677 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004678 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004679 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004680 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004681 if (symbol->getQualifier().hasXfbBuffer())
4682 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4683 if (symbol->getQualifier().hasXfbOffset())
4684 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4685 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004686 // atomic counters use this:
4687 if (symbol->getQualifier().hasOffset())
4688 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004689 }
4690
scygan2c864272016-05-18 18:09:17 +02004691 if (symbol->getQualifier().hasLocation())
4692 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004693 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004694 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004695 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004696 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004697 }
John Kessenich140f3df2015-06-26 16:58:36 -06004698 if (symbol->getQualifier().hasSet())
4699 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004700 else if (IsDescriptorResource(symbol->getType())) {
4701 // default to 0
4702 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4703 }
John Kessenich140f3df2015-06-26 16:58:36 -06004704 if (symbol->getQualifier().hasBinding())
4705 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004706 if (symbol->getQualifier().hasAttachment())
4707 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004708 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004709 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004710 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004711 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004712 if (symbol->getQualifier().hasXfbBuffer())
4713 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4714 }
4715
Rex Xu1da878f2016-02-21 20:59:01 +08004716 if (symbol->getType().isImage()) {
4717 std::vector<spv::Decoration> memory;
4718 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4719 for (unsigned int i = 0; i < memory.size(); ++i)
4720 addDecoration(id, memory[i]);
4721 }
4722
John Kessenich140f3df2015-06-26 16:58:36 -06004723 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004724 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004725 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004726 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004727
chaoc0ad6a4e2016-12-19 16:29:34 -08004728#ifdef NV_EXTENSIONS
4729 if (builtIn == spv::BuiltInSampleMask) {
4730 spv::Decoration decoration;
4731 // GL_NV_sample_mask_override_coverage extension
4732 if (glslangIntermediate->getLayoutOverrideCoverage())
4733 decoration = (spv::Decoration)spv::OverrideCoverageNV;
4734 else
4735 decoration = (spv::Decoration)spv::DecorationMax;
4736 addDecoration(id, decoration);
4737 if (decoration != spv::DecorationMax) {
4738 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4739 }
4740 }
chaoc6e5acae2016-12-20 13:28:52 -08004741 if (symbol->getQualifier().layoutPassthrough) {
4742 addDecoration(id, spv::PassthroughNV);
4743 builder.addCapability(spv::GeometryShaderPassthroughNV);
4744 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4745 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004746#endif
4747
John Kessenich140f3df2015-06-26 16:58:36 -06004748 return id;
4749}
4750
John Kessenich55e7d112015-11-15 21:33:39 -07004751// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004752void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4753{
John Kessenich4016e382016-07-15 11:53:56 -06004754 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004755 builder.addDecoration(id, dec);
4756}
4757
John Kessenich55e7d112015-11-15 21:33:39 -07004758// If 'dec' is valid, add a one-operand decoration to an object
4759void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4760{
John Kessenich4016e382016-07-15 11:53:56 -06004761 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004762 builder.addDecoration(id, dec, value);
4763}
4764
4765// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004766void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4767{
John Kessenich4016e382016-07-15 11:53:56 -06004768 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004769 builder.addMemberDecoration(id, (unsigned)member, dec);
4770}
4771
John Kessenich92187592016-02-01 13:45:25 -07004772// If 'dec' is valid, add a one-operand decoration to a struct member
4773void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4774{
John Kessenich4016e382016-07-15 11:53:56 -06004775 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004776 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4777}
4778
John Kessenich55e7d112015-11-15 21:33:39 -07004779// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004780// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004781//
4782// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4783//
4784// Recursively walk the nodes. The nodes form a tree whose leaves are
4785// regular constants, which themselves are trees that createSpvConstant()
4786// recursively walks. So, this function walks the "top" of the tree:
4787// - emit specialization constant-building instructions for specConstant
4788// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004789spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004790{
John Kessenich7cc0e282016-03-20 00:46:02 -06004791 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004792
qining4f4bb812016-04-03 23:55:17 -04004793 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004794 if (! node.getQualifier().specConstant) {
4795 // hand off to the non-spec-constant path
4796 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4797 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004798 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004799 nextConst, false);
4800 }
4801
4802 // We now know we have a specialization constant to build
4803
John Kessenichd94c0032016-05-30 19:29:40 -06004804 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004805 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4806 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4807 std::vector<spv::Id> dimConstId;
4808 for (int dim = 0; dim < 3; ++dim) {
4809 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4810 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4811 if (specConst)
4812 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4813 }
4814 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4815 }
4816
4817 // An AST node labelled as specialization constant should be a symbol node.
4818 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4819 if (auto* sn = node.getAsSymbolNode()) {
4820 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004821 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4822 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4823 // will set the builder into spec constant op instruction generating mode.
4824 sub_tree->traverse(this);
4825 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004826 } else if (auto* const_union_array = &sn->getConstArray()){
4827 int nextConst = 0;
4828 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004829 }
4830 }
qining4f4bb812016-04-03 23:55:17 -04004831
4832 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4833 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004834 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004835 exit(1);
4836 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004837}
4838
John Kessenich140f3df2015-06-26 16:58:36 -06004839// Use 'consts' as the flattened glslang source of scalar constants to recursively
4840// build the aggregate SPIR-V constant.
4841//
4842// If there are not enough elements present in 'consts', 0 will be substituted;
4843// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4844//
qining08408382016-03-21 09:51:37 -04004845spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004846{
4847 // vector of constants for SPIR-V
4848 std::vector<spv::Id> spvConsts;
4849
4850 // Type is used for struct and array constants
4851 spv::Id typeId = convertGlslangToSpvType(glslangType);
4852
4853 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004854 glslang::TType elementType(glslangType, 0);
4855 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004856 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004857 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004858 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004859 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004860 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004861 } else if (glslangType.getStruct()) {
4862 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4863 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004864 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004865 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004866 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4867 bool zero = nextConst >= consts.size();
4868 switch (glslangType.getBasicType()) {
4869 case glslang::EbtInt:
4870 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4871 break;
4872 case glslang::EbtUint:
4873 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4874 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004875 case glslang::EbtInt64:
4876 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4877 break;
4878 case glslang::EbtUint64:
4879 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4880 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004881 case glslang::EbtFloat:
4882 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4883 break;
4884 case glslang::EbtDouble:
4885 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4886 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004887#ifdef AMD_EXTENSIONS
4888 case glslang::EbtFloat16:
4889 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4890 break;
4891#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004892 case glslang::EbtBool:
4893 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4894 break;
4895 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004896 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004897 break;
4898 }
4899 ++nextConst;
4900 }
4901 } else {
4902 // we have a non-aggregate (scalar) constant
4903 bool zero = nextConst >= consts.size();
4904 spv::Id scalar = 0;
4905 switch (glslangType.getBasicType()) {
4906 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004907 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004908 break;
4909 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004910 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004911 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004912 case glslang::EbtInt64:
4913 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4914 break;
4915 case glslang::EbtUint64:
4916 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4917 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004918 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004919 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004920 break;
4921 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004922 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004923 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004924#ifdef AMD_EXTENSIONS
4925 case glslang::EbtFloat16:
4926 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4927 break;
4928#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004929 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004930 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004931 break;
4932 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004933 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004934 break;
4935 }
4936 ++nextConst;
4937 return scalar;
4938 }
4939
4940 return builder.makeCompositeConstant(typeId, spvConsts);
4941}
4942
John Kessenich7c1aa102015-10-15 13:29:11 -06004943// Return true if the node is a constant or symbol whose reading has no
4944// non-trivial observable cost or effect.
4945bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4946{
4947 // don't know what this is
4948 if (node == nullptr)
4949 return false;
4950
4951 // a constant is safe
4952 if (node->getAsConstantUnion() != nullptr)
4953 return true;
4954
4955 // not a symbol means non-trivial
4956 if (node->getAsSymbolNode() == nullptr)
4957 return false;
4958
4959 // a symbol, depends on what's being read
4960 switch (node->getType().getQualifier().storage) {
4961 case glslang::EvqTemporary:
4962 case glslang::EvqGlobal:
4963 case glslang::EvqIn:
4964 case glslang::EvqInOut:
4965 case glslang::EvqConst:
4966 case glslang::EvqConstReadOnly:
4967 case glslang::EvqUniform:
4968 return true;
4969 default:
4970 return false;
4971 }
qining25262b32016-05-06 17:25:16 -04004972}
John Kessenich7c1aa102015-10-15 13:29:11 -06004973
4974// A node is trivial if it is a single operation with no side effects.
4975// Error on the side of saying non-trivial.
4976// Return true if trivial.
4977bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4978{
4979 if (node == nullptr)
4980 return false;
4981
4982 // symbols and constants are trivial
4983 if (isTrivialLeaf(node))
4984 return true;
4985
4986 // otherwise, it needs to be a simple operation or one or two leaf nodes
4987
4988 // not a simple operation
4989 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4990 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4991 if (binaryNode == nullptr && unaryNode == nullptr)
4992 return false;
4993
4994 // not on leaf nodes
4995 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4996 return false;
4997
4998 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4999 return false;
5000 }
5001
5002 switch (node->getAsOperator()->getOp()) {
5003 case glslang::EOpLogicalNot:
5004 case glslang::EOpConvIntToBool:
5005 case glslang::EOpConvUintToBool:
5006 case glslang::EOpConvFloatToBool:
5007 case glslang::EOpConvDoubleToBool:
5008 case glslang::EOpEqual:
5009 case glslang::EOpNotEqual:
5010 case glslang::EOpLessThan:
5011 case glslang::EOpGreaterThan:
5012 case glslang::EOpLessThanEqual:
5013 case glslang::EOpGreaterThanEqual:
5014 case glslang::EOpIndexDirect:
5015 case glslang::EOpIndexDirectStruct:
5016 case glslang::EOpLogicalXor:
5017 case glslang::EOpAny:
5018 case glslang::EOpAll:
5019 return true;
5020 default:
5021 return false;
5022 }
5023}
5024
5025// Emit short-circuiting code, where 'right' is never evaluated unless
5026// the left side is true (for &&) or false (for ||).
5027spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5028{
5029 spv::Id boolTypeId = builder.makeBoolType();
5030
5031 // emit left operand
5032 builder.clearAccessChain();
5033 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005034 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005035
5036 // Operands to accumulate OpPhi operands
5037 std::vector<spv::Id> phiOperands;
5038 // accumulate left operand's phi information
5039 phiOperands.push_back(leftId);
5040 phiOperands.push_back(builder.getBuildPoint()->getId());
5041
5042 // Make the two kinds of operation symmetric with a "!"
5043 // || => emit "if (! left) result = right"
5044 // && => emit "if ( left) result = right"
5045 //
5046 // TODO: this runtime "not" for || could be avoided by adding functionality
5047 // to 'builder' to have an "else" without an "then"
5048 if (op == glslang::EOpLogicalOr)
5049 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5050
5051 // make an "if" based on the left value
5052 spv::Builder::If ifBuilder(leftId, builder);
5053
5054 // emit right operand as the "then" part of the "if"
5055 builder.clearAccessChain();
5056 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005057 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005058
5059 // accumulate left operand's phi information
5060 phiOperands.push_back(rightId);
5061 phiOperands.push_back(builder.getBuildPoint()->getId());
5062
5063 // finish the "if"
5064 ifBuilder.makeEndIf();
5065
5066 // phi together the two results
5067 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5068}
5069
Rex Xu9d93a232016-05-05 12:30:44 +08005070// Return type Id of the imported set of extended instructions corresponds to the name.
5071// Import this set if it has not been imported yet.
5072spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5073{
5074 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5075 return extBuiltinMap[name];
5076 else {
Rex Xu51596642016-09-21 18:56:12 +08005077 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005078 spv::Id extBuiltins = builder.import(name);
5079 extBuiltinMap[name] = extBuiltins;
5080 return extBuiltins;
5081 }
5082}
5083
John Kessenich140f3df2015-06-26 16:58:36 -06005084}; // end anonymous namespace
5085
5086namespace glslang {
5087
John Kessenich68d78fd2015-07-12 19:28:10 -06005088void GetSpirvVersion(std::string& version)
5089{
John Kessenich9e55f632015-07-15 10:03:39 -06005090 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005091 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005092 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005093 version = buf;
5094}
5095
John Kessenich140f3df2015-06-26 16:58:36 -06005096// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005097void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005098{
5099 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005100 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005101 for (int i = 0; i < (int)spirv.size(); ++i) {
5102 unsigned int word = spirv[i];
5103 out.write((const char*)&word, 4);
5104 }
5105 out.close();
5106}
5107
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005108// Write SPIR-V out to a text file with 32-bit hexadecimal words
5109void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5110{
5111 std::ofstream out;
5112 out.open(baseName, std::ios::binary | std::ios::out);
5113 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5114 const int WORDS_PER_LINE = 8;
5115 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5116 out << "\t";
5117 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5118 const unsigned int word = spirv[i + j];
5119 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5120 if (i + j + 1 < (int)spirv.size()) {
5121 out << ",";
5122 }
5123 }
5124 out << std::endl;
5125 }
5126 out.close();
5127}
5128
John Kessenich140f3df2015-06-26 16:58:36 -06005129//
5130// Set up the glslang traversal
5131//
5132void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5133{
Lei Zhang17535f72016-05-04 15:55:59 -04005134 spv::SpvBuildLogger logger;
5135 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005136}
5137
Lei Zhang17535f72016-05-04 15:55:59 -04005138void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005139{
John Kessenich140f3df2015-06-26 16:58:36 -06005140 TIntermNode* root = intermediate.getTreeRoot();
5141
5142 if (root == 0)
5143 return;
5144
5145 glslang::GetThreadPoolAllocator().push();
5146
Lei Zhang17535f72016-05-04 15:55:59 -04005147 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005148 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005149 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005150 it.dumpSpv(spirv);
5151
5152 glslang::GetThreadPoolAllocator().pop();
5153}
5154
5155}; // end namespace glslang