blob: a7b0f057aa79c3ef176ab60bd51a959e6012d7f2 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
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//
John Kessenich927608b2017-01-06 12:34:14 -070023// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060035
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 Xu430ef402016-10-14 17:22:23 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, 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:
John Kessenich927608b2017-01-06 12:34:14 -0700224 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400225 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::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
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 Kessenich140f3df2015-06-26 16:58:36 -0600265 } else {
266 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
270 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::StorageClassFunction;
274 }
275 }
276}
277
278// Translate glslang sampler type to SPIR-V dimensionality.
279spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
280{
281 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700282 case glslang::Esd1D: return spv::Dim1D;
283 case glslang::Esd2D: return spv::Dim2D;
284 case glslang::Esd3D: return spv::Dim3D;
285 case glslang::EsdCube: return spv::DimCube;
286 case glslang::EsdRect: return spv::DimRect;
287 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700288 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::Dim2D;
292 }
293}
294
John Kessenichf6640762016-08-01 19:44:00 -0600295// Translate glslang precision to SPIR-V precision decorations.
296spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
John Kessenichf6640762016-08-01 19:44:00 -0600298 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700299 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600300 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600301 default:
302 return spv::NoPrecision;
303 }
304}
305
John Kessenichf6640762016-08-01 19:44:00 -0600306// Translate glslang type to SPIR-V precision decorations.
307spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
308{
309 return TranslatePrecisionDecoration(type.getQualifier().precision);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V block decorations.
313spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
314{
315 if (type.getBasicType() == glslang::EbtBlock) {
316 switch (type.getQualifier().storage) {
317 case glslang::EvqUniform: return spv::DecorationBlock;
318 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
319 case glslang::EvqVaryingIn: return spv::DecorationBlock;
320 case glslang::EvqVaryingOut: return spv::DecorationBlock;
321 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600323 break;
324 }
325 }
326
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328}
329
Rex Xu1da878f2016-02-21 20:59:01 +0800330// Translate glslang type to SPIR-V memory decorations.
331void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
332{
333 if (qualifier.coherent)
334 memory.push_back(spv::DecorationCoherent);
335 if (qualifier.volatil)
336 memory.push_back(spv::DecorationVolatile);
337 if (qualifier.restrict)
338 memory.push_back(spv::DecorationRestrict);
339 if (qualifier.readonly)
340 memory.push_back(spv::DecorationNonWritable);
341 if (qualifier.writeonly)
342 memory.push_back(spv::DecorationNonReadable);
343}
344
John Kessenich140f3df2015-06-26 16:58:36 -0600345// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700346spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
348 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElmRowMajor:
351 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 default:
355 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 } else {
359 switch (type.getBasicType()) {
360 default:
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 break;
363 case glslang::EbtBlock:
364 switch (type.getQualifier().storage) {
365 case glslang::EvqUniform:
366 case glslang::EvqBuffer:
367 switch (type.getQualifier().layoutPacking) {
368 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 case glslang::EvqVaryingIn:
374 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 }
382 }
383}
384
385// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600386// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700387// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800388spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
Rex Xubbceed72016-05-21 09:40:44 +0800390 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800393 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800397#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800398 else if (qualifier.explicitInterp) {
399 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800400 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800401 }
Rex Xu9d93a232016-05-05 12:30:44 +0800402#endif
Rex Xubbceed72016-05-21 09:40:44 +0800403 else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800405}
406
407// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800409// should be applied.
410spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
411{
412 if (qualifier.patch)
413 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700416 else if (qualifier.sample) {
417 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700419 } else
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421}
422
John Kessenich92187592016-02-01 13:45:25 -0700423// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600425{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationInvariant;
428 else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
qining9220dbb2016-05-04 17:34:38 -0400432// If glslang type is noContraction, return SPIR-V NoContraction decoration.
433spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
434{
435 if (qualifier.noContraction)
436 return spv::DecorationNoContraction;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400439}
440
David Netoa901ffe2016-06-08 14:11:40 +0100441// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
442// associated capabilities when required. For some built-in variables, a capability
443// is generated only when using the variable in an executable instruction, but not when
444// just declaring a struct member variable with it. This is true for PointSize,
445// ClipDistance, and CullDistance.
446spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
448 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700449 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600450 // Defer adding the capability until the built-in is actually used.
451 if (! memberDeclaration) {
452 switch (glslangIntermediate->getStage()) {
453 case EShLangGeometry:
454 builder.addCapability(spv::CapabilityGeometryPointSize);
455 break;
456 case EShLangTessControl:
457 case EShLangTessEvaluation:
458 builder.addCapability(spv::CapabilityTessellationPointSize);
459 break;
460 default:
461 break;
462 }
John Kessenich92187592016-02-01 13:45:25 -0700463 }
464 return spv::BuiltInPointSize;
465
John Kessenichebb50532016-05-16 19:22:05 -0600466 // These *Distance capabilities logically belong here, but if the member is declared and
467 // then never used, consumers of SPIR-V prefer the capability not be declared.
468 // They are now generated when used, rather than here when declared.
469 // Potentially, the specification should be more clear what the minimum
470 // use needed is to trigger the capability.
471 //
John Kessenich92187592016-02-01 13:45:25 -0700472 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInClipDistance;
476
477 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInCullDistance;
481
482 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500483 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800484#ifdef NV_EXTENSIONS
485 if (glslangIntermediate->getStage() == EShLangVertex ||
486 glslangIntermediate->getStage() == EShLangTessControl ||
487 glslangIntermediate->getStage() == EShLangTessEvaluation)
488 {
489 builder.addExtension(spv::E_SPV_NV_viewport_array2);
490 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
491 }
492#endif
John Kessenich92187592016-02-01 13:45:25 -0700493 return spv::BuiltInViewportIndex;
494
John Kessenich5e801132016-02-15 11:09:46 -0700495 case glslang::EbvSampleId:
496 builder.addCapability(spv::CapabilitySampleRateShading);
497 return spv::BuiltInSampleId;
498
499 case glslang::EbvSamplePosition:
500 builder.addCapability(spv::CapabilitySampleRateShading);
501 return spv::BuiltInSamplePosition;
502
503 case glslang::EbvSampleMask:
504 builder.addCapability(spv::CapabilitySampleRateShading);
505 return spv::BuiltInSampleMask;
506
John Kessenich78a45572016-07-08 14:05:15 -0600507 case glslang::EbvLayer:
508 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800509#ifdef NV_EXTENSIONS
510 if (!memberDeclaration)
511 {
512 if (glslangIntermediate->getStage() == EShLangVertex ||
513 glslangIntermediate->getStage() == EShLangTessControl ||
514 glslangIntermediate->getStage() == EShLangTessEvaluation)
515 {
516 builder.addExtension(spv::E_SPV_NV_viewport_array2);
517 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
518 }
519 }
520#endif
John Kessenich78a45572016-07-08 14:05:15 -0600521 return spv::BuiltInLayer;
522
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvVertexId: return spv::BuiltInVertexId;
525 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700526 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
527 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800528
John Kessenichda581a22015-10-14 14:10:30 -0600529 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800530 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
531 builder.addCapability(spv::CapabilityDrawParameters);
532 return spv::BuiltInBaseVertex;
533
John Kessenichda581a22015-10-14 14:10:30 -0600534 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
536 builder.addCapability(spv::CapabilityDrawParameters);
537 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200538
John Kessenichda581a22015-10-14 14:10:30 -0600539 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
541 builder.addCapability(spv::CapabilityDrawParameters);
542 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200543
544 case glslang::EbvPrimitiveId:
545 if (glslangIntermediate->getStage() == EShLangFragment)
546 builder.addCapability(spv::CapabilityGeometry);
547 return spv::BuiltInPrimitiveId;
548
John Kessenich140f3df2015-06-26 16:58:36 -0600549 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600550 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
551 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
552 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
553 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
554 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
555 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
556 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600557 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
558 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
559 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
560 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
561 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
562 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
563 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
564 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupSize;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLocalInvocationId;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupEqMaskKHR;
580
Rex Xu574ab042016-04-14 16:53:07 +0800581 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800582 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
583 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
584 return spv::BuiltInSubgroupGeMaskKHR;
585
Rex Xu574ab042016-04-14 16:53:07 +0800586 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800587 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
588 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
589 return spv::BuiltInSubgroupGtMaskKHR;
590
Rex Xu574ab042016-04-14 16:53:07 +0800591 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800592 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
593 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
594 return spv::BuiltInSubgroupLeMaskKHR;
595
Rex Xu574ab042016-04-14 16:53:07 +0800596 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800597 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
598 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
599 return spv::BuiltInSubgroupLtMaskKHR;
600
Rex Xu9d93a232016-05-05 12:30:44 +0800601#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800602 case glslang::EbvBaryCoordNoPersp:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordNoPerspAMD;
605
606 case glslang::EbvBaryCoordNoPerspCentroid:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
609
610 case glslang::EbvBaryCoordNoPerspSample:
611 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
612 return spv::BuiltInBaryCoordNoPerspSampleAMD;
613
614 case glslang::EbvBaryCoordSmooth:
615 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
616 return spv::BuiltInBaryCoordSmoothAMD;
617
618 case glslang::EbvBaryCoordSmoothCentroid:
619 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
620 return spv::BuiltInBaryCoordSmoothCentroidAMD;
621
622 case glslang::EbvBaryCoordSmoothSample:
623 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
624 return spv::BuiltInBaryCoordSmoothSampleAMD;
625
626 case glslang::EbvBaryCoordPullModel:
627 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
628 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800629#endif
chaoc771d89f2017-01-13 01:10:53 -0800630
John Kessenich6c8aaac2017-02-27 01:20:51 -0700631 case glslang::EbvDeviceIndex:
632 builder.addExtension(spv::E_SPV_KHR_device_group);
633 builder.addCapability(spv::CapabilityDeviceGroup);
634 return spv::BuiltinDeviceIndex;
635
636 case glslang::EbvViewIndex:
637 builder.addExtension(spv::E_SPV_KHR_multiview);
638 builder.addCapability(spv::CapabilityMultiView);
639 return spv::BuiltinViewIndex;
640
chaoc771d89f2017-01-13 01:10:53 -0800641#ifdef NV_EXTENSIONS
642 case glslang::EbvViewportMaskNV:
643 builder.addExtension(spv::E_SPV_NV_viewport_array2);
644 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
645 return spv::BuiltInViewportMaskNV;
646 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800647 if (!memberDeclaration) {
648 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
649 builder.addCapability(spv::CapabilityShaderStereoViewNV);
650 }
chaoc771d89f2017-01-13 01:10:53 -0800651 return spv::BuiltInSecondaryPositionNV;
652 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800653 if (!memberDeclaration) {
654 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
655 builder.addCapability(spv::CapabilityShaderStereoViewNV);
656 }
chaoc771d89f2017-01-13 01:10:53 -0800657 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800658 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800659 if (!memberDeclaration) {
660 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
661 builder.addCapability(spv::CapabilityPerViewAttributesNV);
662 }
chaocdf3956c2017-02-14 14:52:34 -0800663 return spv::BuiltInPositionPerViewNV;
664 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800665 if (!memberDeclaration) {
666 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
667 builder.addCapability(spv::CapabilityPerViewAttributesNV);
668 }
chaocdf3956c2017-02-14 14:52:34 -0800669 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800670#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800671 default:
672 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600673 }
674}
675
Rex Xufc618912015-09-09 16:42:49 +0800676// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700677spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800678{
679 assert(type.getBasicType() == glslang::EbtSampler);
680
John Kessenich5d0fa972016-02-15 11:57:00 -0700681 // Check for capabilities
682 switch (type.getQualifier().layoutFormat) {
683 case glslang::ElfRg32f:
684 case glslang::ElfRg16f:
685 case glslang::ElfR11fG11fB10f:
686 case glslang::ElfR16f:
687 case glslang::ElfRgba16:
688 case glslang::ElfRgb10A2:
689 case glslang::ElfRg16:
690 case glslang::ElfRg8:
691 case glslang::ElfR16:
692 case glslang::ElfR8:
693 case glslang::ElfRgba16Snorm:
694 case glslang::ElfRg16Snorm:
695 case glslang::ElfRg8Snorm:
696 case glslang::ElfR16Snorm:
697 case glslang::ElfR8Snorm:
698
699 case glslang::ElfRg32i:
700 case glslang::ElfRg16i:
701 case glslang::ElfRg8i:
702 case glslang::ElfR16i:
703 case glslang::ElfR8i:
704
705 case glslang::ElfRgb10a2ui:
706 case glslang::ElfRg32ui:
707 case glslang::ElfRg16ui:
708 case glslang::ElfRg8ui:
709 case glslang::ElfR16ui:
710 case glslang::ElfR8ui:
711 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
712 break;
713
714 default:
715 break;
716 }
717
718 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800719 switch (type.getQualifier().layoutFormat) {
720 case glslang::ElfNone: return spv::ImageFormatUnknown;
721 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
722 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
723 case glslang::ElfR32f: return spv::ImageFormatR32f;
724 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
725 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
726 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
727 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
728 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
729 case glslang::ElfR16f: return spv::ImageFormatR16f;
730 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
731 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
732 case glslang::ElfRg16: return spv::ImageFormatRg16;
733 case glslang::ElfRg8: return spv::ImageFormatRg8;
734 case glslang::ElfR16: return spv::ImageFormatR16;
735 case glslang::ElfR8: return spv::ImageFormatR8;
736 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
737 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
738 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
739 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
740 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
741 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
742 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
743 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
744 case glslang::ElfR32i: return spv::ImageFormatR32i;
745 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
746 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
747 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
748 case glslang::ElfR16i: return spv::ImageFormatR16i;
749 case glslang::ElfR8i: return spv::ImageFormatR8i;
750 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
751 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
752 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
753 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
754 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
755 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
756 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
757 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
758 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
759 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600760 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800761 }
762}
763
qining25262b32016-05-06 17:25:16 -0400764// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700765// descriptor set.
766bool IsDescriptorResource(const glslang::TType& type)
767{
John Kessenichf7497e22016-03-08 21:36:22 -0700768 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700769 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700770 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700771
772 // non block...
773 // basically samplerXXX/subpass/sampler/texture are all included
774 // if they are the global-scope-class, not the function parameter
775 // (or local, if they ever exist) class.
776 if (type.getBasicType() == glslang::EbtSampler)
777 return type.getQualifier().isUniformOrBuffer();
778
779 // None of the above.
780 return false;
781}
782
John Kesseniche0b6cad2015-12-24 10:30:13 -0700783void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
784{
785 if (child.layoutMatrix == glslang::ElmNone)
786 child.layoutMatrix = parent.layoutMatrix;
787
788 if (parent.invariant)
789 child.invariant = true;
790 if (parent.nopersp)
791 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800792#ifdef AMD_EXTENSIONS
793 if (parent.explicitInterp)
794 child.explicitInterp = true;
795#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700796 if (parent.flat)
797 child.flat = true;
798 if (parent.centroid)
799 child.centroid = true;
800 if (parent.patch)
801 child.patch = true;
802 if (parent.sample)
803 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800804 if (parent.coherent)
805 child.coherent = true;
806 if (parent.volatil)
807 child.volatil = true;
808 if (parent.restrict)
809 child.restrict = true;
810 if (parent.readonly)
811 child.readonly = true;
812 if (parent.writeonly)
813 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700814}
815
John Kessenichf2b7f332016-09-01 17:05:23 -0600816bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817{
John Kessenich7b9fa252016-01-21 18:56:57 -0700818 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600819 // - struct members might inherit from a struct declaration
820 // (note that non-block structs don't explicitly inherit,
821 // only implicitly, meaning no decoration involved)
822 // - affect decorations on the struct members
823 // (note smooth does not, and expecting something like volatile
824 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700825 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600826 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700827}
828
John Kessenich140f3df2015-06-26 16:58:36 -0600829//
830// Implement the TGlslangToSpvTraverser class.
831//
832
Lei Zhang17535f72016-05-04 15:55:59 -0400833TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600834 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
835 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400836 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700837 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600838 glslangIntermediate(glslangIntermediate)
839{
840 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
841
842 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700843 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600844 stdBuiltins = builder.import("GLSL.std.450");
845 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600846 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
847 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600848
849 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600850 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
851 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600852 builder.addSourceExtension(it->c_str());
853
854 // Add the top-level modes for this shader.
855
John Kessenich92187592016-02-01 13:45:25 -0700856 if (glslangIntermediate->getXfbMode()) {
857 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600858 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700859 }
John Kessenich140f3df2015-06-26 16:58:36 -0600860
861 unsigned int mode;
862 switch (glslangIntermediate->getStage()) {
863 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600864 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600865 break;
866
867 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
870 break;
871
872 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700875 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
876 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
877 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600878 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600879 }
John Kessenich4016e382016-07-15 11:53:56 -0600880 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600881 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
882
John Kesseniche6903322015-10-13 16:29:02 -0600883 switch (glslangIntermediate->getVertexSpacing()) {
884 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
885 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
886 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600887 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600888 }
John Kessenich4016e382016-07-15 11:53:56 -0600889 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600890 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
891
892 switch (glslangIntermediate->getVertexOrder()) {
893 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
894 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600895 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600896 }
John Kessenich4016e382016-07-15 11:53:56 -0600897 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600898 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
899
900 if (glslangIntermediate->getPointMode())
901 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600902 break;
903
904 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600905 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600906 switch (glslangIntermediate->getInputPrimitive()) {
907 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
908 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
909 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700910 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600911 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600912 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600913 }
John Kessenich4016e382016-07-15 11:53:56 -0600914 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600915 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600916
John Kessenich140f3df2015-06-26 16:58:36 -0600917 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
918
919 switch (glslangIntermediate->getOutputPrimitive()) {
920 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
921 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
922 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600923 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600924 }
John Kessenich4016e382016-07-15 11:53:56 -0600925 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600926 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
927 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
928 break;
929
930 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600931 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600932 if (glslangIntermediate->getPixelCenterInteger())
933 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600934
John Kessenich140f3df2015-06-26 16:58:36 -0600935 if (glslangIntermediate->getOriginUpperLeft())
936 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600937 else
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600939
940 if (glslangIntermediate->getEarlyFragmentTests())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
942
943 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600944 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
945 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600946 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600947 }
John Kessenich4016e382016-07-15 11:53:56 -0600948 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600949 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
950
951 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 break;
954
955 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
958 glslangIntermediate->getLocalSize(1),
959 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600960 break;
961
962 default:
963 break;
964 }
John Kessenich140f3df2015-06-26 16:58:36 -0600965}
966
John Kessenichfca82622016-11-26 13:23:20 -0700967// Finish creating SPV, after the traversal is complete.
968void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700969{
John Kessenich517fe7a2016-11-26 13:31:47 -0700970 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700971 builder.setBuildPoint(shaderEntry->getLastBlock());
972 builder.leaveFunction();
973 }
974
John Kessenich7ba63412015-12-20 17:37:07 -0700975 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100976 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
977 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700978
qiningda397332016-03-09 19:54:03 -0500979 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700980}
981
John Kessenichfca82622016-11-26 13:23:20 -0700982// Write the SPV into 'out'.
983void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600984{
John Kessenichfca82622016-11-26 13:23:20 -0700985 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600986}
987
988//
989// Implement the traversal functions.
990//
991// Return true from interior nodes to have the external traversal
992// continue on to children. Return false if children were
993// already processed.
994//
995
996//
qining25262b32016-05-06 17:25:16 -0400997// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600998// - uniform/input reads
999// - output writes
1000// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1001// - something simple that degenerates into the last bullet
1002//
1003void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1004{
qining75d1d802016-04-06 14:42:01 -04001005 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1006 if (symbol->getType().getQualifier().isSpecConstant())
1007 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1008
John Kessenich140f3df2015-06-26 16:58:36 -06001009 // getSymbolId() will set up all the IO decorations on the first call.
1010 // Formal function parameters were mapped during makeFunctions().
1011 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001012
1013 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1014 if (builder.isPointer(id)) {
1015 spv::StorageClass sc = builder.getStorageClass(id);
1016 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1017 iOSet.insert(id);
1018 }
1019
1020 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001021 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001022 // Prepare to generate code for the access
1023
1024 // L-value chains will be computed left to right. We're on the symbol now,
1025 // which is the left-most part of the access chain, so now is "clear" time,
1026 // followed by setting the base.
1027 builder.clearAccessChain();
1028
1029 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001030 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001031 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001032 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001033 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001034 // These are also pure R-values.
1035 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001036 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001037 builder.setAccessChainRValue(id);
1038 else
1039 builder.setAccessChainLValue(id);
1040 }
1041}
1042
1043bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1044{
qining40887662016-04-03 22:20:42 -04001045 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1046 if (node->getType().getQualifier().isSpecConstant())
1047 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1048
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // First, handle special cases
1050 switch (node->getOp()) {
1051 case glslang::EOpAssign:
1052 case glslang::EOpAddAssign:
1053 case glslang::EOpSubAssign:
1054 case glslang::EOpMulAssign:
1055 case glslang::EOpVectorTimesMatrixAssign:
1056 case glslang::EOpVectorTimesScalarAssign:
1057 case glslang::EOpMatrixTimesScalarAssign:
1058 case glslang::EOpMatrixTimesMatrixAssign:
1059 case glslang::EOpDivAssign:
1060 case glslang::EOpModAssign:
1061 case glslang::EOpAndAssign:
1062 case glslang::EOpInclusiveOrAssign:
1063 case glslang::EOpExclusiveOrAssign:
1064 case glslang::EOpLeftShiftAssign:
1065 case glslang::EOpRightShiftAssign:
1066 // A bin-op assign "a += b" means the same thing as "a = a + b"
1067 // where a is evaluated before b. For a simple assignment, GLSL
1068 // says to evaluate the left before the right. So, always, left
1069 // node then right node.
1070 {
1071 // get the left l-value, save it away
1072 builder.clearAccessChain();
1073 node->getLeft()->traverse(this);
1074 spv::Builder::AccessChain lValue = builder.getAccessChain();
1075
1076 // evaluate the right
1077 builder.clearAccessChain();
1078 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001079 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001080
1081 if (node->getOp() != glslang::EOpAssign) {
1082 // the left is also an r-value
1083 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001084 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001085
1086 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001087 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001088 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001089 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1090 node->getType().getBasicType());
1091
1092 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001093 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001094 }
1095
1096 // store the result
1097 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001098 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001099
1100 // assignments are expressions having an rValue after they are evaluated...
1101 builder.clearAccessChain();
1102 builder.setAccessChainRValue(rValue);
1103 }
1104 return false;
1105 case glslang::EOpIndexDirect:
1106 case glslang::EOpIndexDirectStruct:
1107 {
1108 // Get the left part of the access chain.
1109 node->getLeft()->traverse(this);
1110
1111 // Add the next element in the chain
1112
David Netoa901ffe2016-06-08 14:11:40 +01001113 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001114 if (! node->getLeft()->getType().isArray() &&
1115 node->getLeft()->getType().isVector() &&
1116 node->getOp() == glslang::EOpIndexDirect) {
1117 // This is essentially a hard-coded vector swizzle of size 1,
1118 // so short circuit the access-chain stuff with a swizzle.
1119 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001120 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001121 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001122 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001123 int spvIndex = glslangIndex;
1124 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1125 node->getOp() == glslang::EOpIndexDirectStruct)
1126 {
1127 // This may be, e.g., an anonymous block-member selection, which generally need
1128 // index remapping due to hidden members in anonymous blocks.
1129 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1130 assert(remapper.size() > 0);
1131 spvIndex = remapper[glslangIndex];
1132 }
John Kessenichebb50532016-05-16 19:22:05 -06001133
David Netoa901ffe2016-06-08 14:11:40 +01001134 // normal case for indexing array or structure or block
1135 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1136
1137 // Add capabilities here for accessing PointSize and clip/cull distance.
1138 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001139 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001140 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001141 }
1142 }
1143 return false;
1144 case glslang::EOpIndexIndirect:
1145 {
1146 // Structure or array or vector indirection.
1147 // Will use native SPIR-V access-chain for struct and array indirection;
1148 // matrices are arrays of vectors, so will also work for a matrix.
1149 // Will use the access chain's 'component' for variable index into a vector.
1150
1151 // This adapter is building access chains left to right.
1152 // Set up the access chain to the left.
1153 node->getLeft()->traverse(this);
1154
1155 // save it so that computing the right side doesn't trash it
1156 spv::Builder::AccessChain partial = builder.getAccessChain();
1157
1158 // compute the next index in the chain
1159 builder.clearAccessChain();
1160 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001161 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001162
1163 // restore the saved access chain
1164 builder.setAccessChain(partial);
1165
1166 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001167 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001168 else
John Kessenichfa668da2015-09-13 14:46:30 -06001169 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001170 }
1171 return false;
1172 case glslang::EOpVectorSwizzle:
1173 {
1174 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001175 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001176 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001177 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001178 }
1179 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001180 case glslang::EOpMatrixSwizzle:
1181 logger->missingFunctionality("matrix swizzle");
1182 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001183 case glslang::EOpLogicalOr:
1184 case glslang::EOpLogicalAnd:
1185 {
1186
1187 // These may require short circuiting, but can sometimes be done as straight
1188 // binary operations. The right operand must be short circuited if it has
1189 // side effects, and should probably be if it is complex.
1190 if (isTrivial(node->getRight()->getAsTyped()))
1191 break; // handle below as a normal binary operation
1192 // otherwise, we need to do dynamic short circuiting on the right operand
1193 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1194 builder.clearAccessChain();
1195 builder.setAccessChainRValue(result);
1196 }
1197 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001198 default:
1199 break;
1200 }
1201
1202 // Assume generic binary op...
1203
John Kessenich32cfd492016-02-02 12:37:46 -07001204 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001205 builder.clearAccessChain();
1206 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001207 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001208
John Kessenich32cfd492016-02-02 12:37:46 -07001209 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.clearAccessChain();
1211 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001212 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001215 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001216 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001217 convertGlslangToSpvType(node->getType()), left, right,
1218 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001219
John Kessenich50e57562015-12-21 21:21:11 -07001220 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001221 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001222 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001223 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001224 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001225 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001226 return false;
1227 }
John Kessenich140f3df2015-06-26 16:58:36 -06001228}
1229
1230bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1231{
qining40887662016-04-03 22:20:42 -04001232 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1233 if (node->getType().getQualifier().isSpecConstant())
1234 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1235
John Kessenichfc51d282015-08-19 13:34:18 -06001236 spv::Id result = spv::NoResult;
1237
1238 // try texturing first
1239 result = createImageTextureFunctionCall(node);
1240 if (result != spv::NoResult) {
1241 builder.clearAccessChain();
1242 builder.setAccessChainRValue(result);
1243
1244 return false; // done with this node
1245 }
1246
1247 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001248
1249 if (node->getOp() == glslang::EOpArrayLength) {
1250 // Quite special; won't want to evaluate the operand.
1251
1252 // Normal .length() would have been constant folded by the front-end.
1253 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001254 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001255 assert(node->getOperand()->getType().isRuntimeSizedArray());
1256 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1257 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001258 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1259 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001260
1261 builder.clearAccessChain();
1262 builder.setAccessChainRValue(length);
1263
1264 return false;
1265 }
1266
John Kessenichfc51d282015-08-19 13:34:18 -06001267 // Start by evaluating the operand
1268
John Kessenich8c8505c2016-07-26 12:50:38 -06001269 // Does it need a swizzle inversion? If so, evaluation is inverted;
1270 // operate first on the swizzle base, then apply the swizzle.
1271 spv::Id invertedType = spv::NoType;
1272 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1273 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1274 invertedType = getInvertedSwizzleType(*node->getOperand());
1275
John Kessenich140f3df2015-06-26 16:58:36 -06001276 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001277 if (invertedType != spv::NoType)
1278 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1279 else
1280 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001281
Rex Xufc618912015-09-09 16:42:49 +08001282 spv::Id operand = spv::NoResult;
1283
1284 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1285 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001286 node->getOp() == glslang::EOpAtomicCounter ||
1287 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001288 operand = builder.accessChainGetLValue(); // Special case l-value operands
1289 else
John Kessenich32cfd492016-02-02 12:37:46 -07001290 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001291
John Kessenichf6640762016-08-01 19:44:00 -06001292 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001293 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001294
1295 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001296 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001297 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 // if not, then possibly an operation
1300 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001301 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType)
1305 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1306
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.clearAccessChain();
1308 builder.setAccessChainRValue(result);
1309
1310 return false; // done with this node
1311 }
1312
1313 // it must be a special case, check...
1314 switch (node->getOp()) {
1315 case glslang::EOpPostIncrement:
1316 case glslang::EOpPostDecrement:
1317 case glslang::EOpPreIncrement:
1318 case glslang::EOpPreDecrement:
1319 {
1320 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001321 spv::Id one = 0;
1322 if (node->getBasicType() == glslang::EbtFloat)
1323 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001324 else if (node->getBasicType() == glslang::EbtDouble)
1325 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001326#ifdef AMD_EXTENSIONS
1327 else if (node->getBasicType() == glslang::EbtFloat16)
1328 one = builder.makeFloat16Constant(1.0F);
1329#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001330 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1331 one = builder.makeInt64Constant(1);
1332 else
1333 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001334 glslang::TOperator op;
1335 if (node->getOp() == glslang::EOpPreIncrement ||
1336 node->getOp() == glslang::EOpPostIncrement)
1337 op = glslang::EOpAdd;
1338 else
1339 op = glslang::EOpSub;
1340
John Kessenichf6640762016-08-01 19:44:00 -06001341 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001342 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001343 convertGlslangToSpvType(node->getType()), operand, one,
1344 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001345 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001346
1347 // The result of operation is always stored, but conditionally the
1348 // consumed result. The consumed result is always an r-value.
1349 builder.accessChainStore(result);
1350 builder.clearAccessChain();
1351 if (node->getOp() == glslang::EOpPreIncrement ||
1352 node->getOp() == glslang::EOpPreDecrement)
1353 builder.setAccessChainRValue(result);
1354 else
1355 builder.setAccessChainRValue(operand);
1356 }
1357
1358 return false;
1359
1360 case glslang::EOpEmitStreamVertex:
1361 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1362 return false;
1363 case glslang::EOpEndStreamPrimitive:
1364 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1365 return false;
1366
1367 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001368 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001369 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001370 }
John Kessenich140f3df2015-06-26 16:58:36 -06001371}
1372
1373bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1374{
qining27e04a02016-04-14 16:40:20 -04001375 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1376 if (node->getType().getQualifier().isSpecConstant())
1377 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1378
John Kessenichfc51d282015-08-19 13:34:18 -06001379 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001380 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1381 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001382
1383 // try texturing
1384 result = createImageTextureFunctionCall(node);
1385 if (result != spv::NoResult) {
1386 builder.clearAccessChain();
1387 builder.setAccessChainRValue(result);
1388
1389 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001390 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001391 // "imageStore" is a special case, which has no result
1392 return false;
1393 }
John Kessenichfc51d282015-08-19 13:34:18 -06001394
John Kessenich140f3df2015-06-26 16:58:36 -06001395 glslang::TOperator binOp = glslang::EOpNull;
1396 bool reduceComparison = true;
1397 bool isMatrix = false;
1398 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001399 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001400
1401 assert(node->getOp());
1402
John Kessenichf6640762016-08-01 19:44:00 -06001403 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
1405 switch (node->getOp()) {
1406 case glslang::EOpSequence:
1407 {
1408 if (preVisit)
1409 ++sequenceDepth;
1410 else
1411 --sequenceDepth;
1412
1413 if (sequenceDepth == 1) {
1414 // If this is the parent node of all the functions, we want to see them
1415 // early, so all call points have actual SPIR-V functions to reference.
1416 // In all cases, still let the traverser visit the children for us.
1417 makeFunctions(node->getAsAggregate()->getSequence());
1418
John Kessenich6fccb3c2016-09-19 16:01:41 -06001419 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001420 // anything else gets there, so visit out of order, doing them all now.
1421 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1422
John Kessenich6a60c2f2016-12-08 21:01:59 -07001423 // 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 -06001424 // so do them manually.
1425 visitFunctions(node->getAsAggregate()->getSequence());
1426
1427 return false;
1428 }
1429
1430 return true;
1431 }
1432 case glslang::EOpLinkerObjects:
1433 {
1434 if (visit == glslang::EvPreVisit)
1435 linkageOnly = true;
1436 else
1437 linkageOnly = false;
1438
1439 return true;
1440 }
1441 case glslang::EOpComma:
1442 {
1443 // processing from left to right naturally leaves the right-most
1444 // lying around in the access chain
1445 glslang::TIntermSequence& glslangOperands = node->getSequence();
1446 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1447 glslangOperands[i]->traverse(this);
1448
1449 return false;
1450 }
1451 case glslang::EOpFunction:
1452 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001453 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001454 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001456 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001457 } else {
1458 handleFunctionEntry(node);
1459 }
1460 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001461 if (inEntryPoint)
1462 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001463 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001464 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 }
1466
1467 return true;
1468 case glslang::EOpParameters:
1469 // Parameters will have been consumed by EOpFunction processing, but not
1470 // the body, so we still visited the function node's children, making this
1471 // child redundant.
1472 return false;
1473 case glslang::EOpFunctionCall:
1474 {
1475 if (node->isUserDefined())
1476 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001477 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001478 if (result) {
1479 builder.clearAccessChain();
1480 builder.setAccessChainRValue(result);
1481 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001482 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001483
1484 return false;
1485 }
1486 case glslang::EOpConstructMat2x2:
1487 case glslang::EOpConstructMat2x3:
1488 case glslang::EOpConstructMat2x4:
1489 case glslang::EOpConstructMat3x2:
1490 case glslang::EOpConstructMat3x3:
1491 case glslang::EOpConstructMat3x4:
1492 case glslang::EOpConstructMat4x2:
1493 case glslang::EOpConstructMat4x3:
1494 case glslang::EOpConstructMat4x4:
1495 case glslang::EOpConstructDMat2x2:
1496 case glslang::EOpConstructDMat2x3:
1497 case glslang::EOpConstructDMat2x4:
1498 case glslang::EOpConstructDMat3x2:
1499 case glslang::EOpConstructDMat3x3:
1500 case glslang::EOpConstructDMat3x4:
1501 case glslang::EOpConstructDMat4x2:
1502 case glslang::EOpConstructDMat4x3:
1503 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001504#ifdef AMD_EXTENSIONS
1505 case glslang::EOpConstructF16Mat2x2:
1506 case glslang::EOpConstructF16Mat2x3:
1507 case glslang::EOpConstructF16Mat2x4:
1508 case glslang::EOpConstructF16Mat3x2:
1509 case glslang::EOpConstructF16Mat3x3:
1510 case glslang::EOpConstructF16Mat3x4:
1511 case glslang::EOpConstructF16Mat4x2:
1512 case glslang::EOpConstructF16Mat4x3:
1513 case glslang::EOpConstructF16Mat4x4:
1514#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001515 isMatrix = true;
1516 // fall through
1517 case glslang::EOpConstructFloat:
1518 case glslang::EOpConstructVec2:
1519 case glslang::EOpConstructVec3:
1520 case glslang::EOpConstructVec4:
1521 case glslang::EOpConstructDouble:
1522 case glslang::EOpConstructDVec2:
1523 case glslang::EOpConstructDVec3:
1524 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001525#ifdef AMD_EXTENSIONS
1526 case glslang::EOpConstructFloat16:
1527 case glslang::EOpConstructF16Vec2:
1528 case glslang::EOpConstructF16Vec3:
1529 case glslang::EOpConstructF16Vec4:
1530#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EOpConstructBool:
1532 case glslang::EOpConstructBVec2:
1533 case glslang::EOpConstructBVec3:
1534 case glslang::EOpConstructBVec4:
1535 case glslang::EOpConstructInt:
1536 case glslang::EOpConstructIVec2:
1537 case glslang::EOpConstructIVec3:
1538 case glslang::EOpConstructIVec4:
1539 case glslang::EOpConstructUint:
1540 case glslang::EOpConstructUVec2:
1541 case glslang::EOpConstructUVec3:
1542 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001543 case glslang::EOpConstructInt64:
1544 case glslang::EOpConstructI64Vec2:
1545 case glslang::EOpConstructI64Vec3:
1546 case glslang::EOpConstructI64Vec4:
1547 case glslang::EOpConstructUint64:
1548 case glslang::EOpConstructU64Vec2:
1549 case glslang::EOpConstructU64Vec3:
1550 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001551 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001552 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001553 {
1554 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001555 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001556 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001557 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001558 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001559 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001560 std::vector<spv::Id> constituents;
1561 for (int c = 0; c < (int)arguments.size(); ++c)
1562 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001563 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001564 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001565 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001566 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001567 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001568
1569 builder.clearAccessChain();
1570 builder.setAccessChainRValue(constructed);
1571
1572 return false;
1573 }
1574
1575 // These six are component-wise compares with component-wise results.
1576 // Forward on to createBinaryOperation(), requesting a vector result.
1577 case glslang::EOpLessThan:
1578 case glslang::EOpGreaterThan:
1579 case glslang::EOpLessThanEqual:
1580 case glslang::EOpGreaterThanEqual:
1581 case glslang::EOpVectorEqual:
1582 case glslang::EOpVectorNotEqual:
1583 {
1584 // Map the operation to a binary
1585 binOp = node->getOp();
1586 reduceComparison = false;
1587 switch (node->getOp()) {
1588 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1589 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1590 default: binOp = node->getOp(); break;
1591 }
1592
1593 break;
1594 }
1595 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001596 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001597 binOp = glslang::EOpMul;
1598 break;
1599 case glslang::EOpOuterProduct:
1600 // two vectors multiplied to make a matrix
1601 binOp = glslang::EOpOuterProduct;
1602 break;
1603 case glslang::EOpDot:
1604 {
qining25262b32016-05-06 17:25:16 -04001605 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001606 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001607 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001608 binOp = glslang::EOpMul;
1609 break;
1610 }
1611 case glslang::EOpMod:
1612 // when an aggregate, this is the floating-point mod built-in function,
1613 // which can be emitted by the one in createBinaryOperation()
1614 binOp = glslang::EOpMod;
1615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001616 case glslang::EOpEmitVertex:
1617 case glslang::EOpEndPrimitive:
1618 case glslang::EOpBarrier:
1619 case glslang::EOpMemoryBarrier:
1620 case glslang::EOpMemoryBarrierAtomicCounter:
1621 case glslang::EOpMemoryBarrierBuffer:
1622 case glslang::EOpMemoryBarrierImage:
1623 case glslang::EOpMemoryBarrierShared:
1624 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001625 case glslang::EOpAllMemoryBarrierWithGroupSync:
1626 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1627 case glslang::EOpWorkgroupMemoryBarrier:
1628 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001629 noReturnValue = true;
1630 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1631 break;
1632
John Kessenich426394d2015-07-23 10:22:48 -06001633 case glslang::EOpAtomicAdd:
1634 case glslang::EOpAtomicMin:
1635 case glslang::EOpAtomicMax:
1636 case glslang::EOpAtomicAnd:
1637 case glslang::EOpAtomicOr:
1638 case glslang::EOpAtomicXor:
1639 case glslang::EOpAtomicExchange:
1640 case glslang::EOpAtomicCompSwap:
1641 atomic = true;
1642 break;
1643
John Kessenich140f3df2015-06-26 16:58:36 -06001644 default:
1645 break;
1646 }
1647
1648 //
1649 // See if it maps to a regular operation.
1650 //
John Kessenich140f3df2015-06-26 16:58:36 -06001651 if (binOp != glslang::EOpNull) {
1652 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1653 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1654 assert(left && right);
1655
1656 builder.clearAccessChain();
1657 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001658 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001659
1660 builder.clearAccessChain();
1661 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001662 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001663
qining25262b32016-05-06 17:25:16 -04001664 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001665 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001666 left->getType().getBasicType(), reduceComparison);
1667
1668 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001669 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 builder.clearAccessChain();
1671 builder.setAccessChainRValue(result);
1672
1673 return false;
1674 }
1675
John Kessenich426394d2015-07-23 10:22:48 -06001676 //
1677 // Create the list of operands.
1678 //
John Kessenich140f3df2015-06-26 16:58:36 -06001679 glslang::TIntermSequence& glslangOperands = node->getSequence();
1680 std::vector<spv::Id> operands;
1681 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001682 // special case l-value operands; there are just a few
1683 bool lvalue = false;
1684 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001685 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001686 case glslang::EOpModf:
1687 if (arg == 1)
1688 lvalue = true;
1689 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001690 case glslang::EOpInterpolateAtSample:
1691 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001692#ifdef AMD_EXTENSIONS
1693 case glslang::EOpInterpolateAtVertex:
1694#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001695 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001696 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001697
1698 // Does it need a swizzle inversion? If so, evaluation is inverted;
1699 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001700 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001701 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1702 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1703 }
Rex Xu7a26c172015-12-08 17:12:09 +08001704 break;
Rex Xud4782c12015-09-06 16:30:11 +08001705 case glslang::EOpAtomicAdd:
1706 case glslang::EOpAtomicMin:
1707 case glslang::EOpAtomicMax:
1708 case glslang::EOpAtomicAnd:
1709 case glslang::EOpAtomicOr:
1710 case glslang::EOpAtomicXor:
1711 case glslang::EOpAtomicExchange:
1712 case glslang::EOpAtomicCompSwap:
1713 if (arg == 0)
1714 lvalue = true;
1715 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001716 case glslang::EOpAddCarry:
1717 case glslang::EOpSubBorrow:
1718 if (arg == 2)
1719 lvalue = true;
1720 break;
1721 case glslang::EOpUMulExtended:
1722 case glslang::EOpIMulExtended:
1723 if (arg >= 2)
1724 lvalue = true;
1725 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001726 default:
1727 break;
1728 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001729 builder.clearAccessChain();
1730 if (invertedType != spv::NoType && arg == 0)
1731 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1732 else
1733 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001734 if (lvalue)
1735 operands.push_back(builder.accessChainGetLValue());
1736 else
John Kessenich32cfd492016-02-02 12:37:46 -07001737 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001738 }
John Kessenich426394d2015-07-23 10:22:48 -06001739
1740 if (atomic) {
1741 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001742 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001743 } else {
1744 // Pass through to generic operations.
1745 switch (glslangOperands.size()) {
1746 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 break;
1749 case 1:
qining25262b32016-05-06 17:25:16 -04001750 result = createUnaryOperation(
1751 node->getOp(), precision,
1752 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001753 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001754 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001755 break;
1756 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001758 break;
1759 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001760 if (invertedType)
1761 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763
1764 if (noReturnValue)
1765 return false;
1766
1767 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001768 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001769 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001770 } else {
1771 builder.clearAccessChain();
1772 builder.setAccessChainRValue(result);
1773 return false;
1774 }
1775}
1776
John Kessenich433e9ff2017-01-26 20:31:11 -07001777// This path handles both if-then-else and ?:
1778// The if-then-else has a node type of void, while
1779// ?: has either a void or a non-void node type
1780//
1781// Leaving the result, when not void:
1782// GLSL only has r-values as the result of a :?, but
1783// if we have an l-value, that can be more efficient if it will
1784// become the base of a complex r-value expression, because the
1785// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001786bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1787{
John Kessenich433e9ff2017-01-26 20:31:11 -07001788 // See if it simple and safe to generate OpSelect instead of using control flow.
1789 // Crucially, side effects must be avoided, and there are performance trade-offs.
1790 // Return true if good idea (and safe) for OpSelect, false otherwise.
1791 const auto selectPolicy = [&]() -> bool {
1792 if (node->getBasicType() == glslang::EbtVoid)
1793 return false;
1794
1795 if (node->getTrueBlock() == nullptr ||
1796 node->getFalseBlock() == nullptr)
1797 return false;
1798
1799 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1800 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1801
1802 // return true if a single operand to ? : is okay for OpSelect
1803 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001804 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001805 };
1806
1807 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1808 operandOkay(node->getFalseBlock()->getAsTyped());
1809 };
1810
1811 // Emit OpSelect for this selection.
1812 const auto handleAsOpSelect = [&]() {
1813 node->getCondition()->traverse(this);
1814 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1815 node->getTrueBlock()->traverse(this);
1816 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1817 node->getFalseBlock()->traverse(this);
1818 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1819
1820 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1821 builder.clearAccessChain();
1822 builder.setAccessChainRValue(select);
1823 };
1824
1825 // Try for OpSelect
1826
1827 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001828 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1829 if (node->getType().getQualifier().isSpecConstant())
1830 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1831
John Kessenich433e9ff2017-01-26 20:31:11 -07001832 handleAsOpSelect();
1833 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001834 }
1835
John Kessenich433e9ff2017-01-26 20:31:11 -07001836 // Instead, emit control flow...
1837
1838 // Don't handle results as temporaries, because there will be two names
1839 // and better to leave SSA to later passes.
1840 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1841 ? spv::NoResult
1842 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1843
John Kessenich140f3df2015-06-26 16:58:36 -06001844 // emit the condition before doing anything with selection
1845 node->getCondition()->traverse(this);
1846
1847 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001848 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001849
John Kessenich433e9ff2017-01-26 20:31:11 -07001850 // emit the "then" statement
1851 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001852 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001853 if (result != spv::NoResult)
1854 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001855 }
1856
John Kessenich433e9ff2017-01-26 20:31:11 -07001857 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 ifBuilder.makeBeginElse();
1859 // emit the "else" statement
1860 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001861 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001862 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001863 }
1864
John Kessenich433e9ff2017-01-26 20:31:11 -07001865 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001866 ifBuilder.makeEndIf();
1867
John Kessenich433e9ff2017-01-26 20:31:11 -07001868 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001869 // GLSL only has r-values as the result of a :?, but
1870 // if we have an l-value, that can be more efficient if it will
1871 // become the base of a complex r-value expression, because the
1872 // next layer copies r-values into memory to use the access-chain mechanism
1873 builder.clearAccessChain();
1874 builder.setAccessChainLValue(result);
1875 }
1876
1877 return false;
1878}
1879
1880bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1881{
1882 // emit and get the condition before doing anything with switch
1883 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001884 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001885
1886 // browse the children to sort out code segments
1887 int defaultSegment = -1;
1888 std::vector<TIntermNode*> codeSegments;
1889 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1890 std::vector<int> caseValues;
1891 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1892 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1893 TIntermNode* child = *c;
1894 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001895 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001896 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001897 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001898 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1899 } else
1900 codeSegments.push_back(child);
1901 }
1902
qining25262b32016-05-06 17:25:16 -04001903 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001904 // statements between the last case and the end of the switch statement
1905 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1906 (int)codeSegments.size() == defaultSegment)
1907 codeSegments.push_back(nullptr);
1908
1909 // make the switch statement
1910 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001911 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001912
1913 // emit all the code in the segments
1914 breakForLoop.push(false);
1915 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1916 builder.nextSwitchSegment(segmentBlocks, s);
1917 if (codeSegments[s])
1918 codeSegments[s]->traverse(this);
1919 else
1920 builder.addSwitchBreak();
1921 }
1922 breakForLoop.pop();
1923
1924 builder.endSwitch(segmentBlocks);
1925
1926 return false;
1927}
1928
1929void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1930{
1931 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001932 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001933
1934 builder.clearAccessChain();
1935 builder.setAccessChainRValue(constant);
1936}
1937
1938bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1939{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001940 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001941 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001942 // Spec requires back edges to target header blocks, and every header block
1943 // must dominate its merge block. Make a header block first to ensure these
1944 // conditions are met. By definition, it will contain OpLoopMerge, followed
1945 // by a block-ending branch. But we don't want to put any other body/test
1946 // instructions in it, since the body/test may have arbitrary instructions,
1947 // including merges of its own.
1948 builder.setBuildPoint(&blocks.head);
1949 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001950 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001951 spv::Block& test = builder.makeNewBlock();
1952 builder.createBranch(&test);
1953
1954 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001955 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001956 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001957 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001958 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1959
1960 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001961 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001962 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001963 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001964 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001965 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001966
1967 builder.setBuildPoint(&blocks.continue_target);
1968 if (node->getTerminal())
1969 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001970 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001971 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001972 builder.createBranch(&blocks.body);
1973
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001974 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001975 builder.setBuildPoint(&blocks.body);
1976 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001977 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001978 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001979 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001980
1981 builder.setBuildPoint(&blocks.continue_target);
1982 if (node->getTerminal())
1983 node->getTerminal()->traverse(this);
1984 if (node->getTest()) {
1985 node->getTest()->traverse(this);
1986 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001987 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001988 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001989 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001990 // TODO: unless there was a break/return/discard instruction
1991 // somewhere in the body, this is an infinite loop, so we should
1992 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001993 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001994 }
John Kessenich140f3df2015-06-26 16:58:36 -06001995 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001996 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001997 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001998 return false;
1999}
2000
2001bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2002{
2003 if (node->getExpression())
2004 node->getExpression()->traverse(this);
2005
2006 switch (node->getFlowOp()) {
2007 case glslang::EOpKill:
2008 builder.makeDiscard();
2009 break;
2010 case glslang::EOpBreak:
2011 if (breakForLoop.top())
2012 builder.createLoopExit();
2013 else
2014 builder.addSwitchBreak();
2015 break;
2016 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002017 builder.createLoopContinue();
2018 break;
2019 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002020 if (node->getExpression()) {
2021 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2022 spv::Id returnId = accessChainLoad(glslangReturnType);
2023 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2024 builder.clearAccessChain();
2025 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2026 builder.setAccessChainLValue(copyId);
2027 multiTypeStore(glslangReturnType, returnId);
2028 returnId = builder.createLoad(copyId);
2029 }
2030 builder.makeReturn(false, returnId);
2031 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002032 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002033
2034 builder.clearAccessChain();
2035 break;
2036
2037 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002038 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002039 break;
2040 }
2041
2042 return false;
2043}
2044
2045spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2046{
qining25262b32016-05-06 17:25:16 -04002047 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002048 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002049 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002050 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002051 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002052 }
2053
2054 // Now, handle actual variables
2055 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2056 spv::Id spvType = convertGlslangToSpvType(node->getType());
2057
2058 const char* name = node->getName().c_str();
2059 if (glslang::IsAnonymous(name))
2060 name = "";
2061
2062 return builder.createVariable(storageClass, spvType, name);
2063}
2064
2065// Return type Id of the sampled type.
2066spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2067{
2068 switch (sampler.type) {
2069 case glslang::EbtFloat: return builder.makeFloatType(32);
2070 case glslang::EbtInt: return builder.makeIntType(32);
2071 case glslang::EbtUint: return builder.makeUintType(32);
2072 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002073 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002074 return builder.makeFloatType(32);
2075 }
2076}
2077
John Kessenich8c8505c2016-07-26 12:50:38 -06002078// If node is a swizzle operation, return the type that should be used if
2079// the swizzle base is first consumed by another operation, before the swizzle
2080// is applied.
2081spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2082{
John Kessenichecba76f2017-01-06 00:34:48 -07002083 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002084 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2085 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2086 else
2087 return spv::NoType;
2088}
2089
2090// When inverting a swizzle with a parent op, this function
2091// will apply the swizzle operation to a completed parent operation.
2092spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2093{
2094 std::vector<unsigned> swizzle;
2095 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2096 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2097}
2098
John Kessenich8c8505c2016-07-26 12:50:38 -06002099// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2100void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2101{
2102 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2103 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2104 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2105}
2106
John Kessenich3ac051e2015-12-20 11:29:16 -07002107// Convert from a glslang type to an SPV type, by calling into a
2108// recursive version of this function. This establishes the inherited
2109// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002110spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2111{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002112 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002113}
2114
2115// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002116// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002117// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002118spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002119{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002120 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002121
2122 switch (type.getBasicType()) {
2123 case glslang::EbtVoid:
2124 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002125 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002126 break;
2127 case glslang::EbtFloat:
2128 spvType = builder.makeFloatType(32);
2129 break;
2130 case glslang::EbtDouble:
2131 spvType = builder.makeFloatType(64);
2132 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002133#ifdef AMD_EXTENSIONS
2134 case glslang::EbtFloat16:
2135 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002136 spvType = builder.makeFloatType(16);
2137 break;
2138#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002139 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002140 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2141 // a 32-bit int where non-0 means true.
2142 if (explicitLayout != glslang::ElpNone)
2143 spvType = builder.makeUintType(32);
2144 else
2145 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002146 break;
2147 case glslang::EbtInt:
2148 spvType = builder.makeIntType(32);
2149 break;
2150 case glslang::EbtUint:
2151 spvType = builder.makeUintType(32);
2152 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002153 case glslang::EbtInt64:
2154 builder.addCapability(spv::CapabilityInt64);
2155 spvType = builder.makeIntType(64);
2156 break;
2157 case glslang::EbtUint64:
2158 builder.addCapability(spv::CapabilityInt64);
2159 spvType = builder.makeUintType(64);
2160 break;
John Kessenich426394d2015-07-23 10:22:48 -06002161 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002162 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002163 spvType = builder.makeUintType(32);
2164 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002165 case glslang::EbtSampler:
2166 {
2167 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002168 if (sampler.sampler) {
2169 // pure sampler
2170 spvType = builder.makeSamplerType();
2171 } else {
2172 // an image is present, make its type
2173 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2174 sampler.image ? 2 : 1, TranslateImageFormat(type));
2175 if (sampler.combined) {
2176 // already has both image and sampler, make the combined type
2177 spvType = builder.makeSampledImageType(spvType);
2178 }
John Kessenich55e7d112015-11-15 21:33:39 -07002179 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002180 }
John Kessenich140f3df2015-06-26 16:58:36 -06002181 break;
2182 case glslang::EbtStruct:
2183 case glslang::EbtBlock:
2184 {
2185 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002186 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002187
2188 // Try to share structs for different layouts, but not yet for other
2189 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002190 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002191 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002192 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002193 break;
2194
2195 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002196 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002197 memberRemapper[glslangMembers].resize(glslangMembers->size());
2198 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002199 }
2200 break;
2201 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002202 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002203 break;
2204 }
2205
2206 if (type.isMatrix())
2207 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2208 else {
2209 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2210 if (type.getVectorSize() > 1)
2211 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2212 }
2213
2214 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002215 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2216
John Kessenichc9a80832015-09-12 12:17:44 -06002217 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002218 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002219 // We need to decorate array strides for types needing explicit layout, except blocks.
2220 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002221 // Use a dummy glslang type for querying internal strides of
2222 // arrays of arrays, but using just a one-dimensional array.
2223 glslang::TType simpleArrayType(type, 0); // deference type of the array
2224 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2225 simpleArrayType.getArraySizes().dereference();
2226
2227 // Will compute the higher-order strides here, rather than making a whole
2228 // pile of types and doing repetitive recursion on their contents.
2229 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2230 }
John Kessenichf8842e52016-01-04 19:22:56 -07002231
2232 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002233 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002234 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002235 if (stride > 0)
2236 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002237 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002238 }
2239 } else {
2240 // single-dimensional array, and don't yet have stride
2241
John Kessenichf8842e52016-01-04 19:22:56 -07002242 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002243 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2244 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002245 }
John Kessenich31ed4832015-09-09 17:51:38 -06002246
John Kessenichc9a80832015-09-12 12:17:44 -06002247 // Do the outer dimension, which might not be known for a runtime-sized array
2248 if (type.isRuntimeSizedArray()) {
2249 spvType = builder.makeRuntimeArray(spvType);
2250 } else {
2251 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002252 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002253 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002254 if (stride > 0)
2255 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002256 }
2257
2258 return spvType;
2259}
2260
John Kessenich6090df02016-06-30 21:18:02 -06002261// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2262// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2263// Mutually recursive with convertGlslangToSpvType().
2264spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2265 const glslang::TTypeList* glslangMembers,
2266 glslang::TLayoutPacking explicitLayout,
2267 const glslang::TQualifier& qualifier)
2268{
2269 // Create a vector of struct types for SPIR-V to consume
2270 std::vector<spv::Id> spvMembers;
2271 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2272 int locationOffset = 0; // for use across struct members, when they are called recursively
2273 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2274 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2275 if (glslangMember.hiddenMember()) {
2276 ++memberDelta;
2277 if (type.getBasicType() == glslang::EbtBlock)
2278 memberRemapper[glslangMembers][i] = -1;
2279 } else {
2280 if (type.getBasicType() == glslang::EbtBlock)
2281 memberRemapper[glslangMembers][i] = i - memberDelta;
2282 // modify just this child's view of the qualifier
2283 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2284 InheritQualifiers(memberQualifier, qualifier);
2285
2286 // manually inherit location; it's more complex
2287 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2288 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2289 if (qualifier.hasLocation())
2290 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2291
2292 // recurse
2293 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2294 }
2295 }
2296
2297 // Make the SPIR-V type
2298 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002299 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002300 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2301
2302 // Decorate it
2303 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2304
2305 return spvType;
2306}
2307
2308void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2309 const glslang::TTypeList* glslangMembers,
2310 glslang::TLayoutPacking explicitLayout,
2311 const glslang::TQualifier& qualifier,
2312 spv::Id spvType)
2313{
2314 // Name and decorate the non-hidden members
2315 int offset = -1;
2316 int locationOffset = 0; // for use within the members of this struct
2317 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2318 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2319 int member = i;
2320 if (type.getBasicType() == glslang::EbtBlock)
2321 member = memberRemapper[glslangMembers][i];
2322
2323 // modify just this child's view of the qualifier
2324 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2325 InheritQualifiers(memberQualifier, qualifier);
2326
2327 // using -1 above to indicate a hidden member
2328 if (member >= 0) {
2329 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2330 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2331 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2332 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002333 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2334 type.getQualifier().storage == glslang::EvqVaryingOut) {
2335 if (type.getBasicType() == glslang::EbtBlock ||
2336 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002337 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2338 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2339 }
2340 }
2341 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2342
2343 if (qualifier.storage == glslang::EvqBuffer) {
2344 std::vector<spv::Decoration> memory;
2345 TranslateMemoryDecoration(memberQualifier, memory);
2346 for (unsigned int i = 0; i < memory.size(); ++i)
2347 addMemberDecoration(spvType, member, memory[i]);
2348 }
2349
John Kessenich2f47bc92016-06-30 21:47:35 -06002350 // Compute location decoration; tricky based on whether inheritance is at play and
2351 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002352 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2353 // probably move to the linker stage of the front end proper, and just have the
2354 // answer sitting already distributed throughout the individual member locations.
2355 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002356 // Ignore member locations if the container is an array, as that's
2357 // ill-specified and decisions have been made to not allow this anyway.
2358 // The object itself must have a location, and that comes out from decorating the object,
2359 // not the type (this code decorates types).
2360 if (! type.isArray()) {
2361 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2362 // struct members should not have explicit locations
2363 assert(type.getBasicType() != glslang::EbtStruct);
2364 location = memberQualifier.layoutLocation;
2365 } else if (type.getBasicType() != glslang::EbtBlock) {
2366 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2367 // The members, and their nested types, must not themselves have Location decorations.
2368 } else if (qualifier.hasLocation()) // inheritance
2369 location = qualifier.layoutLocation + locationOffset;
2370 }
John Kessenich6090df02016-06-30 21:18:02 -06002371 if (location >= 0)
2372 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2373
John Kessenich2f47bc92016-06-30 21:47:35 -06002374 if (qualifier.hasLocation()) // track for upcoming inheritance
2375 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2376
John Kessenich6090df02016-06-30 21:18:02 -06002377 // component, XFB, others
2378 if (glslangMember.getQualifier().hasComponent())
2379 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2380 if (glslangMember.getQualifier().hasXfbOffset())
2381 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2382 else if (explicitLayout != glslang::ElpNone) {
2383 // figure out what to do with offset, which is accumulating
2384 int nextOffset;
2385 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2386 if (offset >= 0)
2387 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2388 offset = nextOffset;
2389 }
2390
2391 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2392 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2393
2394 // built-in variable decorations
2395 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002396 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002397 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002398
2399#ifdef NV_EXTENSIONS
2400 if (builtIn == spv::BuiltInLayer) {
2401 // SPV_NV_viewport_array2 extension
2402 if (glslangMember.getQualifier().layoutViewportRelative){
2403 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2404 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2405 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2406 }
2407 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2408 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2409 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2410 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2411 }
2412 }
chaocdf3956c2017-02-14 14:52:34 -08002413 if (glslangMember.getQualifier().layoutPassthrough) {
2414 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2415 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2416 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2417 }
chaoc771d89f2017-01-13 01:10:53 -08002418#endif
John Kessenich6090df02016-06-30 21:18:02 -06002419 }
2420 }
2421
2422 // Decorate the structure
2423 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2424 addDecoration(spvType, TranslateBlockDecoration(type));
2425 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2426 builder.addCapability(spv::CapabilityGeometryStreams);
2427 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2428 }
2429 if (glslangIntermediate->getXfbMode()) {
2430 builder.addCapability(spv::CapabilityTransformFeedback);
2431 if (type.getQualifier().hasXfbStride())
2432 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2433 if (type.getQualifier().hasXfbBuffer())
2434 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2435 }
2436}
2437
John Kessenich6c292d32016-02-15 20:58:50 -07002438// Turn the expression forming the array size into an id.
2439// This is not quite trivial, because of specialization constants.
2440// Sometimes, a raw constant is turned into an Id, and sometimes
2441// a specialization constant expression is.
2442spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2443{
2444 // First, see if this is sized with a node, meaning a specialization constant:
2445 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2446 if (specNode != nullptr) {
2447 builder.clearAccessChain();
2448 specNode->traverse(this);
2449 return accessChainLoad(specNode->getAsTyped()->getType());
2450 }
qining25262b32016-05-06 17:25:16 -04002451
John Kessenich6c292d32016-02-15 20:58:50 -07002452 // Otherwise, need a compile-time (front end) size, get it:
2453 int size = arraySizes.getDimSize(dim);
2454 assert(size > 0);
2455 return builder.makeUintConstant(size);
2456}
2457
John Kessenich103bef92016-02-08 21:38:15 -07002458// Wrap the builder's accessChainLoad to:
2459// - localize handling of RelaxedPrecision
2460// - use the SPIR-V inferred type instead of another conversion of the glslang type
2461// (avoids unnecessary work and possible type punning for structures)
2462// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002463spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2464{
John Kessenich103bef92016-02-08 21:38:15 -07002465 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2466 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2467
2468 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002469 if (type.getBasicType() == glslang::EbtBool) {
2470 if (builder.isScalarType(nominalTypeId)) {
2471 // Conversion for bool
2472 spv::Id boolType = builder.makeBoolType();
2473 if (nominalTypeId != boolType)
2474 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2475 } else if (builder.isVectorType(nominalTypeId)) {
2476 // Conversion for bvec
2477 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2478 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2479 if (nominalTypeId != bvecType)
2480 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2481 }
2482 }
John Kessenich103bef92016-02-08 21:38:15 -07002483
2484 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002485}
2486
Rex Xu27253232016-02-23 17:51:09 +08002487// Wrap the builder's accessChainStore to:
2488// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002489//
2490// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002491void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2492{
2493 // Need to convert to abstract types when necessary
2494 if (type.getBasicType() == glslang::EbtBool) {
2495 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2496
2497 if (builder.isScalarType(nominalTypeId)) {
2498 // Conversion for bool
2499 spv::Id boolType = builder.makeBoolType();
2500 if (nominalTypeId != boolType) {
2501 spv::Id zero = builder.makeUintConstant(0);
2502 spv::Id one = builder.makeUintConstant(1);
2503 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2504 }
2505 } else if (builder.isVectorType(nominalTypeId)) {
2506 // Conversion for bvec
2507 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2508 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2509 if (nominalTypeId != bvecType) {
2510 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2511 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2512 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2513 }
2514 }
2515 }
2516
2517 builder.accessChainStore(rvalue);
2518}
2519
John Kessenich4bf71552016-09-02 11:20:21 -06002520// For storing when types match at the glslang level, but not might match at the
2521// SPIR-V level.
2522//
2523// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002524// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002525// as in a member-decorated way.
2526//
2527// NOTE: This function can handle any store request; if it's not special it
2528// simplifies to a simple OpStore.
2529//
2530// Implicitly uses the existing builder.accessChain as the storage target.
2531void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2532{
John Kessenichb3e24e42016-09-11 12:33:43 -06002533 // we only do the complex path here if it's an aggregate
2534 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002535 accessChainStore(type, rValue);
2536 return;
2537 }
2538
John Kessenichb3e24e42016-09-11 12:33:43 -06002539 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002540 spv::Id rType = builder.getTypeId(rValue);
2541 spv::Id lValue = builder.accessChainGetLValue();
2542 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2543 if (lType == rType) {
2544 accessChainStore(type, rValue);
2545 return;
2546 }
2547
John Kessenichb3e24e42016-09-11 12:33:43 -06002548 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002549 // where the two types were the same type in GLSL. This requires member
2550 // by member copy, recursively.
2551
John Kessenichb3e24e42016-09-11 12:33:43 -06002552 // If an array, copy element by element.
2553 if (type.isArray()) {
2554 glslang::TType glslangElementType(type, 0);
2555 spv::Id elementRType = builder.getContainedTypeId(rType);
2556 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2557 // get the source member
2558 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002559
John Kessenichb3e24e42016-09-11 12:33:43 -06002560 // set up the target storage
2561 builder.clearAccessChain();
2562 builder.setAccessChainLValue(lValue);
2563 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002564
John Kessenichb3e24e42016-09-11 12:33:43 -06002565 // store the member
2566 multiTypeStore(glslangElementType, elementRValue);
2567 }
2568 } else {
2569 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002570
John Kessenichb3e24e42016-09-11 12:33:43 -06002571 // loop over structure members
2572 const glslang::TTypeList& members = *type.getStruct();
2573 for (int m = 0; m < (int)members.size(); ++m) {
2574 const glslang::TType& glslangMemberType = *members[m].type;
2575
2576 // get the source member
2577 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2578 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2579
2580 // set up the target storage
2581 builder.clearAccessChain();
2582 builder.setAccessChainLValue(lValue);
2583 builder.accessChainPush(builder.makeIntConstant(m));
2584
2585 // store the member
2586 multiTypeStore(glslangMemberType, memberRValue);
2587 }
John Kessenich4bf71552016-09-02 11:20:21 -06002588 }
2589}
2590
John Kessenichf85e8062015-12-19 13:57:10 -07002591// Decide whether or not this type should be
2592// decorated with offsets and strides, and if so
2593// whether std140 or std430 rules should be applied.
2594glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002595{
John Kessenichf85e8062015-12-19 13:57:10 -07002596 // has to be a block
2597 if (type.getBasicType() != glslang::EbtBlock)
2598 return glslang::ElpNone;
2599
2600 // has to be a uniform or buffer block
2601 if (type.getQualifier().storage != glslang::EvqUniform &&
2602 type.getQualifier().storage != glslang::EvqBuffer)
2603 return glslang::ElpNone;
2604
2605 // return the layout to use
2606 switch (type.getQualifier().layoutPacking) {
2607 case glslang::ElpStd140:
2608 case glslang::ElpStd430:
2609 return type.getQualifier().layoutPacking;
2610 default:
2611 return glslang::ElpNone;
2612 }
John Kessenich31ed4832015-09-09 17:51:38 -06002613}
2614
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002615// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002616int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002617{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002618 int size;
John Kessenich49987892015-12-29 17:11:44 -07002619 int stride;
2620 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002621
2622 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002623}
2624
John Kessenich49987892015-12-29 17:11:44 -07002625// 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 -07002626// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002627int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002628{
John Kessenich49987892015-12-29 17:11:44 -07002629 glslang::TType elementType;
2630 elementType.shallowCopy(matrixType);
2631 elementType.clearArraySizes();
2632
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002633 int size;
John Kessenich49987892015-12-29 17:11:44 -07002634 int stride;
2635 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2636
2637 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002638}
2639
John Kessenich5e4b1242015-08-06 22:53:06 -06002640// Given a member type of a struct, realign the current offset for it, and compute
2641// the next (not yet aligned) offset for the next member, which will get aligned
2642// on the next call.
2643// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2644// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2645// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002646void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002647 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002648{
2649 // this will get a positive value when deemed necessary
2650 nextOffset = -1;
2651
John Kessenich5e4b1242015-08-06 22:53:06 -06002652 // override anything in currentOffset with user-set offset
2653 if (memberType.getQualifier().hasOffset())
2654 currentOffset = memberType.getQualifier().layoutOffset;
2655
2656 // It could be that current linker usage in glslang updated all the layoutOffset,
2657 // in which case the following code does not matter. But, that's not quite right
2658 // once cross-compilation unit GLSL validation is done, as the original user
2659 // settings are needed in layoutOffset, and then the following will come into play.
2660
John Kessenichf85e8062015-12-19 13:57:10 -07002661 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002662 if (! memberType.getQualifier().hasOffset())
2663 currentOffset = -1;
2664
2665 return;
2666 }
2667
John Kessenichf85e8062015-12-19 13:57:10 -07002668 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002669 if (currentOffset < 0)
2670 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002671
John Kessenich5e4b1242015-08-06 22:53:06 -06002672 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2673 // but possibly not yet correctly aligned.
2674
2675 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002676 int dummyStride;
2677 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002678 glslang::RoundToPow2(currentOffset, memberAlignment);
2679 nextOffset = currentOffset + memberSize;
2680}
2681
David Netoa901ffe2016-06-08 14:11:40 +01002682void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002683{
David Netoa901ffe2016-06-08 14:11:40 +01002684 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2685 switch (glslangBuiltIn)
2686 {
2687 case glslang::EbvClipDistance:
2688 case glslang::EbvCullDistance:
2689 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002690#ifdef NV_EXTENSIONS
2691 case glslang::EbvLayer:
2692 case glslang::EbvViewportMaskNV:
2693 case glslang::EbvSecondaryPositionNV:
2694 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002695 case glslang::EbvPositionPerViewNV:
2696 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002697#endif
David Netoa901ffe2016-06-08 14:11:40 +01002698 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2699 // Alternately, we could just call this for any glslang built-in, since the
2700 // capability already guards against duplicates.
2701 TranslateBuiltInDecoration(glslangBuiltIn, false);
2702 break;
2703 default:
2704 // Capabilities were already generated when the struct was declared.
2705 break;
2706 }
John Kessenichebb50532016-05-16 19:22:05 -06002707}
2708
John Kessenich6fccb3c2016-09-19 16:01:41 -06002709bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002710{
John Kessenicheee9d532016-09-19 18:09:30 -06002711 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002712}
2713
2714// Make all the functions, skeletally, without actually visiting their bodies.
2715void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2716{
2717 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2718 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002719 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002720 continue;
2721
2722 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002723 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002724 //
qining25262b32016-05-06 17:25:16 -04002725 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002726 // function. What it is an address of varies:
2727 //
John Kessenich4bf71552016-09-02 11:20:21 -06002728 // - "in" parameters not marked as "const" can be written to without modifying the calling
2729 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002730 //
2731 // - "const in" parameters can just be the r-value, as no writes need occur.
2732 //
John Kessenich4bf71552016-09-02 11:20:21 -06002733 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2734 // 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 -06002735
2736 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002737 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002738 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2739
2740 for (int p = 0; p < (int)parameters.size(); ++p) {
2741 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2742 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich4a57dce2017-02-24 19:15:46 -07002743 if (paramType.containsOpaque())
Jason Ekstranded15ef12016-06-08 13:54:48 -07002744 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2745 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002746 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2747 else
John Kessenich4bf71552016-09-02 11:20:21 -06002748 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002749 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002750 paramTypes.push_back(typeId);
2751 }
2752
2753 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002754 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2755 convertGlslangToSpvType(glslFunction->getType()),
2756 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002757
2758 // Track function to emit/call later
2759 functionMap[glslFunction->getName().c_str()] = function;
2760
2761 // Set the parameter id's
2762 for (int p = 0; p < (int)parameters.size(); ++p) {
2763 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2764 // give a name too
2765 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2766 }
2767 }
2768}
2769
2770// Process all the initializers, while skipping the functions and link objects
2771void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2772{
2773 builder.setBuildPoint(shaderEntry->getLastBlock());
2774 for (int i = 0; i < (int)initializers.size(); ++i) {
2775 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2776 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2777
2778 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002779 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002780 initializer->traverse(this);
2781 }
2782 }
2783}
2784
2785// Process all the functions, while skipping initializers.
2786void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2787{
2788 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2789 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002790 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002791 node->traverse(this);
2792 }
2793}
2794
2795void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2796{
qining25262b32016-05-06 17:25:16 -04002797 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002798 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002799 currentFunction = functionMap[node->getName().c_str()];
2800 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002801 builder.setBuildPoint(functionBlock);
2802}
2803
Rex Xu04db3f52015-09-16 11:44:02 +08002804void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002805{
Rex Xufc618912015-09-09 16:42:49 +08002806 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002807
2808 glslang::TSampler sampler = {};
2809 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002810 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002811 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2812 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2813 }
2814
John Kessenich140f3df2015-06-26 16:58:36 -06002815 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2816 builder.clearAccessChain();
2817 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002818
2819 // Special case l-value operands
2820 bool lvalue = false;
2821 switch (node.getOp()) {
2822 case glslang::EOpImageAtomicAdd:
2823 case glslang::EOpImageAtomicMin:
2824 case glslang::EOpImageAtomicMax:
2825 case glslang::EOpImageAtomicAnd:
2826 case glslang::EOpImageAtomicOr:
2827 case glslang::EOpImageAtomicXor:
2828 case glslang::EOpImageAtomicExchange:
2829 case glslang::EOpImageAtomicCompSwap:
2830 if (i == 0)
2831 lvalue = true;
2832 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002833 case glslang::EOpSparseImageLoad:
2834 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2835 lvalue = true;
2836 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002837 case glslang::EOpSparseTexture:
2838 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2839 lvalue = true;
2840 break;
2841 case glslang::EOpSparseTextureClamp:
2842 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2843 lvalue = true;
2844 break;
2845 case glslang::EOpSparseTextureLod:
2846 case glslang::EOpSparseTextureOffset:
2847 if (i == 3)
2848 lvalue = true;
2849 break;
2850 case glslang::EOpSparseTextureFetch:
2851 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2852 lvalue = true;
2853 break;
2854 case glslang::EOpSparseTextureFetchOffset:
2855 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2856 lvalue = true;
2857 break;
2858 case glslang::EOpSparseTextureLodOffset:
2859 case glslang::EOpSparseTextureGrad:
2860 case glslang::EOpSparseTextureOffsetClamp:
2861 if (i == 4)
2862 lvalue = true;
2863 break;
2864 case glslang::EOpSparseTextureGradOffset:
2865 case glslang::EOpSparseTextureGradClamp:
2866 if (i == 5)
2867 lvalue = true;
2868 break;
2869 case glslang::EOpSparseTextureGradOffsetClamp:
2870 if (i == 6)
2871 lvalue = true;
2872 break;
2873 case glslang::EOpSparseTextureGather:
2874 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2875 lvalue = true;
2876 break;
2877 case glslang::EOpSparseTextureGatherOffset:
2878 case glslang::EOpSparseTextureGatherOffsets:
2879 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2880 lvalue = true;
2881 break;
Rex Xufc618912015-09-09 16:42:49 +08002882 default:
2883 break;
2884 }
2885
Rex Xu6b86d492015-09-16 17:48:22 +08002886 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002887 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002888 else
John Kessenich32cfd492016-02-02 12:37:46 -07002889 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002890 }
2891}
2892
John Kessenichfc51d282015-08-19 13:34:18 -06002893void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002894{
John Kessenichfc51d282015-08-19 13:34:18 -06002895 builder.clearAccessChain();
2896 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002897 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002898}
John Kessenich140f3df2015-06-26 16:58:36 -06002899
John Kessenichfc51d282015-08-19 13:34:18 -06002900spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2901{
Rex Xufc618912015-09-09 16:42:49 +08002902 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002903 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002904 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002905 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002906
John Kessenichfc51d282015-08-19 13:34:18 -06002907 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002908 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2909 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2910 std::vector<spv::Id> arguments;
2911 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002912 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002913 else
2914 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002915 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002916
2917 spv::Builder::TextureParameters params = { };
2918 params.sampler = arguments[0];
2919
Rex Xu04db3f52015-09-16 11:44:02 +08002920 glslang::TCrackedTextureOp cracked;
2921 node->crackTexture(sampler, cracked);
2922
John Kessenichfc51d282015-08-19 13:34:18 -06002923 // Check for queries
2924 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002925 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2926 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002927 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002928
John Kessenichfc51d282015-08-19 13:34:18 -06002929 switch (node->getOp()) {
2930 case glslang::EOpImageQuerySize:
2931 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002932 if (arguments.size() > 1) {
2933 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002935 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002936 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002937 case glslang::EOpImageQuerySamples:
2938 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002939 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002940 case glslang::EOpTextureQueryLod:
2941 params.coords = arguments[1];
2942 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2943 case glslang::EOpTextureQueryLevels:
2944 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002945 case glslang::EOpSparseTexelsResident:
2946 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002947 default:
2948 assert(0);
2949 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002950 }
John Kessenich140f3df2015-06-26 16:58:36 -06002951 }
2952
Rex Xufc618912015-09-09 16:42:49 +08002953 // Check for image functions other than queries
2954 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002955 std::vector<spv::Id> operands;
2956 auto opIt = arguments.begin();
2957 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002958
2959 // Handle subpass operations
2960 // TODO: GLSL should change to have the "MS" only on the type rather than the
2961 // built-in function.
2962 if (cracked.subpass) {
2963 // add on the (0,0) coordinate
2964 spv::Id zero = builder.makeIntConstant(0);
2965 std::vector<spv::Id> comps;
2966 comps.push_back(zero);
2967 comps.push_back(zero);
2968 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2969 if (sampler.ms) {
2970 operands.push_back(spv::ImageOperandsSampleMask);
2971 operands.push_back(*(opIt++));
2972 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002973 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002974 }
2975
John Kessenich56bab042015-09-16 10:54:31 -06002976 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002977 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002978 if (sampler.ms) {
2979 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002980 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002981 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002982 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2983 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002984 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002985 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002986 if (sampler.ms) {
2987 operands.push_back(*(opIt + 1));
2988 operands.push_back(spv::ImageOperandsSampleMask);
2989 operands.push_back(*opIt);
2990 } else
2991 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002992 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002993 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2994 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002995 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002996 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2997 builder.addCapability(spv::CapabilitySparseResidency);
2998 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2999 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3000
3001 if (sampler.ms) {
3002 operands.push_back(spv::ImageOperandsSampleMask);
3003 operands.push_back(*opIt++);
3004 }
3005
3006 // Create the return type that was a special structure
3007 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003008 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003009 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3010 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3011
3012 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3013
3014 // Decode the return type
3015 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3016 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003017 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003018 // Process image atomic operations
3019
3020 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3021 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003022 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003023
John Kessenich8c8505c2016-07-26 12:50:38 -06003024 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003025 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003026
3027 std::vector<spv::Id> operands;
3028 operands.push_back(pointer);
3029 for (; opIt != arguments.end(); ++opIt)
3030 operands.push_back(*opIt);
3031
John Kessenich8c8505c2016-07-26 12:50:38 -06003032 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003033 }
3034 }
3035
3036 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003037 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003038 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3039
John Kessenichfc51d282015-08-19 13:34:18 -06003040 // check for bias argument
3041 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003042 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003043 int nonBiasArgCount = 2;
3044 if (cracked.offset)
3045 ++nonBiasArgCount;
3046 if (cracked.grad)
3047 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003048 if (cracked.lodClamp)
3049 ++nonBiasArgCount;
3050 if (sparse)
3051 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003052
3053 if ((int)arguments.size() > nonBiasArgCount)
3054 bias = true;
3055 }
3056
John Kessenicha5c33d62016-06-02 23:45:21 -06003057 // See if the sampler param should really be just the SPV image part
3058 if (cracked.fetch) {
3059 // a fetch needs to have the image extracted first
3060 if (builder.isSampledImage(params.sampler))
3061 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3062 }
3063
John Kessenichfc51d282015-08-19 13:34:18 -06003064 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003065
John Kessenichfc51d282015-08-19 13:34:18 -06003066 params.coords = arguments[1];
3067 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003068 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003069
3070 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003071 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003072 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003073 ++extraArgs;
3074 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003075 params.Dref = arguments[2];
3076 ++extraArgs;
3077 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003078 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003079 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003080 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003081 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003082 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003083 dRefComp = builder.getNumComponents(params.coords) - 1;
3084 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003085 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3086 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003087
3088 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003089 if (cracked.lod) {
3090 params.lod = arguments[2];
3091 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003092 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3093 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3094 noImplicitLod = true;
3095 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003096
3097 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003098 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003099 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003100 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003101 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003102
3103 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003104 if (cracked.grad) {
3105 params.gradX = arguments[2 + extraArgs];
3106 params.gradY = arguments[3 + extraArgs];
3107 extraArgs += 2;
3108 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003109
3110 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003111 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003112 params.offset = arguments[2 + extraArgs];
3113 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003114 } else if (cracked.offsets) {
3115 params.offsets = arguments[2 + extraArgs];
3116 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003117 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003118
3119 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003120 if (cracked.lodClamp) {
3121 params.lodClamp = arguments[2 + extraArgs];
3122 ++extraArgs;
3123 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003124
3125 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003126 if (sparse) {
3127 params.texelOut = arguments[2 + extraArgs];
3128 ++extraArgs;
3129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003130
3131 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003132 if (bias) {
3133 params.bias = arguments[2 + extraArgs];
3134 ++extraArgs;
3135 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003136
3137 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003138 if (cracked.gather && ! sampler.shadow) {
3139 // default component is 0, if missing, otherwise an argument
3140 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003141 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003142 ++extraArgs;
3143 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003144 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003145 }
3146 }
John Kessenichfc51d282015-08-19 13:34:18 -06003147
John Kessenich65336482016-06-16 14:06:26 -06003148 // projective component (might not to move)
3149 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3150 // are divided by the last component of P."
3151 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3152 // unused components will appear after all used components."
3153 if (cracked.proj) {
3154 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3155 int projTargetComp;
3156 switch (sampler.dim) {
3157 case glslang::Esd1D: projTargetComp = 1; break;
3158 case glslang::Esd2D: projTargetComp = 2; break;
3159 case glslang::EsdRect: projTargetComp = 2; break;
3160 default: projTargetComp = projSourceComp; break;
3161 }
3162 // copy the projective coordinate if we have to
3163 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003164 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003165 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3166 projSourceComp);
3167 params.coords = builder.createCompositeInsert(projComp, params.coords,
3168 builder.getTypeId(params.coords), projTargetComp);
3169 }
3170 }
3171
John Kessenich8c8505c2016-07-26 12:50:38 -06003172 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003173}
3174
3175spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3176{
3177 // Grab the function's pointer from the previously created function
3178 spv::Function* function = functionMap[node->getName().c_str()];
3179 if (! function)
3180 return 0;
3181
3182 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3183 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3184
3185 // See comments in makeFunctions() for details about the semantics for parameter passing.
3186 //
3187 // These imply we need a four step process:
3188 // 1. Evaluate the arguments
3189 // 2. Allocate and make copies of in, out, and inout arguments
3190 // 3. Make the call
3191 // 4. Copy back the results
3192
3193 // 1. Evaluate the arguments
3194 std::vector<spv::Builder::AccessChain> lValues;
3195 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003196 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003197 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003198 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003199 // build l-value
3200 builder.clearAccessChain();
3201 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003202 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003203 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003204 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003205 // save l-value
3206 lValues.push_back(builder.getAccessChain());
3207 } else {
3208 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003209 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003210 }
3211 }
3212
3213 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3214 // copy the original into that space.
3215 //
3216 // Also, build up the list of actual arguments to pass in for the call
3217 int lValueCount = 0;
3218 int rValueCount = 0;
3219 std::vector<spv::Id> spvArgs;
3220 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003221 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003222 spv::Id arg;
John Kessenich4a57dce2017-02-24 19:15:46 -07003223 if (paramType.containsOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003224 builder.setAccessChain(lValues[lValueCount]);
3225 arg = builder.accessChainGetLValue();
3226 ++lValueCount;
3227 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003228 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003229 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3230 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3231 // need to copy the input into output space
3232 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003233 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003234 builder.clearAccessChain();
3235 builder.setAccessChainLValue(arg);
3236 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003237 }
3238 ++lValueCount;
3239 } else {
3240 arg = rValues[rValueCount];
3241 ++rValueCount;
3242 }
3243 spvArgs.push_back(arg);
3244 }
3245
3246 // 3. Make the call.
3247 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003248 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003249
3250 // 4. Copy back out an "out" arguments.
3251 lValueCount = 0;
3252 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003253 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003254 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3255 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3256 spv::Id copy = builder.createLoad(spvArgs[a]);
3257 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003258 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003259 }
3260 ++lValueCount;
3261 }
3262 }
3263
3264 return result;
3265}
3266
3267// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003268spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3269 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003270 spv::Id typeId, spv::Id left, spv::Id right,
3271 glslang::TBasicType typeProxy, bool reduceComparison)
3272{
Rex Xu8ff43de2016-04-22 16:51:45 +08003273 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003274#ifdef AMD_EXTENSIONS
3275 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3276#else
John Kessenich140f3df2015-06-26 16:58:36 -06003277 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003278#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003279 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003280
3281 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003282 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003283 bool comparison = false;
3284
3285 switch (op) {
3286 case glslang::EOpAdd:
3287 case glslang::EOpAddAssign:
3288 if (isFloat)
3289 binOp = spv::OpFAdd;
3290 else
3291 binOp = spv::OpIAdd;
3292 break;
3293 case glslang::EOpSub:
3294 case glslang::EOpSubAssign:
3295 if (isFloat)
3296 binOp = spv::OpFSub;
3297 else
3298 binOp = spv::OpISub;
3299 break;
3300 case glslang::EOpMul:
3301 case glslang::EOpMulAssign:
3302 if (isFloat)
3303 binOp = spv::OpFMul;
3304 else
3305 binOp = spv::OpIMul;
3306 break;
3307 case glslang::EOpVectorTimesScalar:
3308 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003309 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003310 if (builder.isVector(right))
3311 std::swap(left, right);
3312 assert(builder.isScalar(right));
3313 needMatchingVectors = false;
3314 binOp = spv::OpVectorTimesScalar;
3315 } else
3316 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318 case glslang::EOpVectorTimesMatrix:
3319 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003320 binOp = spv::OpVectorTimesMatrix;
3321 break;
3322 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003323 binOp = spv::OpMatrixTimesVector;
3324 break;
3325 case glslang::EOpMatrixTimesScalar:
3326 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003327 binOp = spv::OpMatrixTimesScalar;
3328 break;
3329 case glslang::EOpMatrixTimesMatrix:
3330 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003331 binOp = spv::OpMatrixTimesMatrix;
3332 break;
3333 case glslang::EOpOuterProduct:
3334 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003335 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003336 break;
3337
3338 case glslang::EOpDiv:
3339 case glslang::EOpDivAssign:
3340 if (isFloat)
3341 binOp = spv::OpFDiv;
3342 else if (isUnsigned)
3343 binOp = spv::OpUDiv;
3344 else
3345 binOp = spv::OpSDiv;
3346 break;
3347 case glslang::EOpMod:
3348 case glslang::EOpModAssign:
3349 if (isFloat)
3350 binOp = spv::OpFMod;
3351 else if (isUnsigned)
3352 binOp = spv::OpUMod;
3353 else
3354 binOp = spv::OpSMod;
3355 break;
3356 case glslang::EOpRightShift:
3357 case glslang::EOpRightShiftAssign:
3358 if (isUnsigned)
3359 binOp = spv::OpShiftRightLogical;
3360 else
3361 binOp = spv::OpShiftRightArithmetic;
3362 break;
3363 case glslang::EOpLeftShift:
3364 case glslang::EOpLeftShiftAssign:
3365 binOp = spv::OpShiftLeftLogical;
3366 break;
3367 case glslang::EOpAnd:
3368 case glslang::EOpAndAssign:
3369 binOp = spv::OpBitwiseAnd;
3370 break;
3371 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003372 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 binOp = spv::OpLogicalAnd;
3374 break;
3375 case glslang::EOpInclusiveOr:
3376 case glslang::EOpInclusiveOrAssign:
3377 binOp = spv::OpBitwiseOr;
3378 break;
3379 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003380 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003381 binOp = spv::OpLogicalOr;
3382 break;
3383 case glslang::EOpExclusiveOr:
3384 case glslang::EOpExclusiveOrAssign:
3385 binOp = spv::OpBitwiseXor;
3386 break;
3387 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003388 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003389 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003390 break;
3391
3392 case glslang::EOpLessThan:
3393 case glslang::EOpGreaterThan:
3394 case glslang::EOpLessThanEqual:
3395 case glslang::EOpGreaterThanEqual:
3396 case glslang::EOpEqual:
3397 case glslang::EOpNotEqual:
3398 case glslang::EOpVectorEqual:
3399 case glslang::EOpVectorNotEqual:
3400 comparison = true;
3401 break;
3402 default:
3403 break;
3404 }
3405
John Kessenich7c1aa102015-10-15 13:29:11 -06003406 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003407 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003408 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003409 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003410 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003411
3412 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003413 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003414 builder.promoteScalar(precision, left, right);
3415
qining25262b32016-05-06 17:25:16 -04003416 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3417 addDecoration(result, noContraction);
3418 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003419 }
3420
3421 if (! comparison)
3422 return 0;
3423
John Kessenich7c1aa102015-10-15 13:29:11 -06003424 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003425
John Kessenich4583b612016-08-07 19:14:22 -06003426 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3427 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003428 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003429
3430 switch (op) {
3431 case glslang::EOpLessThan:
3432 if (isFloat)
3433 binOp = spv::OpFOrdLessThan;
3434 else if (isUnsigned)
3435 binOp = spv::OpULessThan;
3436 else
3437 binOp = spv::OpSLessThan;
3438 break;
3439 case glslang::EOpGreaterThan:
3440 if (isFloat)
3441 binOp = spv::OpFOrdGreaterThan;
3442 else if (isUnsigned)
3443 binOp = spv::OpUGreaterThan;
3444 else
3445 binOp = spv::OpSGreaterThan;
3446 break;
3447 case glslang::EOpLessThanEqual:
3448 if (isFloat)
3449 binOp = spv::OpFOrdLessThanEqual;
3450 else if (isUnsigned)
3451 binOp = spv::OpULessThanEqual;
3452 else
3453 binOp = spv::OpSLessThanEqual;
3454 break;
3455 case glslang::EOpGreaterThanEqual:
3456 if (isFloat)
3457 binOp = spv::OpFOrdGreaterThanEqual;
3458 else if (isUnsigned)
3459 binOp = spv::OpUGreaterThanEqual;
3460 else
3461 binOp = spv::OpSGreaterThanEqual;
3462 break;
3463 case glslang::EOpEqual:
3464 case glslang::EOpVectorEqual:
3465 if (isFloat)
3466 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003467 else if (isBool)
3468 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 else
3470 binOp = spv::OpIEqual;
3471 break;
3472 case glslang::EOpNotEqual:
3473 case glslang::EOpVectorNotEqual:
3474 if (isFloat)
3475 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003476 else if (isBool)
3477 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003478 else
3479 binOp = spv::OpINotEqual;
3480 break;
3481 default:
3482 break;
3483 }
3484
qining25262b32016-05-06 17:25:16 -04003485 if (binOp != spv::OpNop) {
3486 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3487 addDecoration(result, noContraction);
3488 return builder.setPrecision(result, precision);
3489 }
John Kessenich140f3df2015-06-26 16:58:36 -06003490
3491 return 0;
3492}
3493
John Kessenich04bb8a02015-12-12 12:28:14 -07003494//
3495// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3496// These can be any of:
3497//
3498// matrix * scalar
3499// scalar * matrix
3500// matrix * matrix linear algebraic
3501// matrix * vector
3502// vector * matrix
3503// matrix * matrix componentwise
3504// matrix op matrix op in {+, -, /}
3505// matrix op scalar op in {+, -, /}
3506// scalar op matrix op in {+, -, /}
3507//
qining25262b32016-05-06 17:25:16 -04003508spv::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 -07003509{
3510 bool firstClass = true;
3511
3512 // First, handle first-class matrix operations (* and matrix/scalar)
3513 switch (op) {
3514 case spv::OpFDiv:
3515 if (builder.isMatrix(left) && builder.isScalar(right)) {
3516 // turn matrix / scalar into a multiply...
3517 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3518 op = spv::OpMatrixTimesScalar;
3519 } else
3520 firstClass = false;
3521 break;
3522 case spv::OpMatrixTimesScalar:
3523 if (builder.isMatrix(right))
3524 std::swap(left, right);
3525 assert(builder.isScalar(right));
3526 break;
3527 case spv::OpVectorTimesMatrix:
3528 assert(builder.isVector(left));
3529 assert(builder.isMatrix(right));
3530 break;
3531 case spv::OpMatrixTimesVector:
3532 assert(builder.isMatrix(left));
3533 assert(builder.isVector(right));
3534 break;
3535 case spv::OpMatrixTimesMatrix:
3536 assert(builder.isMatrix(left));
3537 assert(builder.isMatrix(right));
3538 break;
3539 default:
3540 firstClass = false;
3541 break;
3542 }
3543
qining25262b32016-05-06 17:25:16 -04003544 if (firstClass) {
3545 spv::Id result = builder.createBinOp(op, typeId, left, right);
3546 addDecoration(result, noContraction);
3547 return builder.setPrecision(result, precision);
3548 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003549
LoopDawg592860c2016-06-09 08:57:35 -06003550 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003551 // The result type of all of them is the same type as the (a) matrix operand.
3552 // The algorithm is to:
3553 // - break the matrix(es) into vectors
3554 // - smear any scalar to a vector
3555 // - do vector operations
3556 // - make a matrix out the vector results
3557 switch (op) {
3558 case spv::OpFAdd:
3559 case spv::OpFSub:
3560 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003561 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003562 case spv::OpFMul:
3563 {
3564 // one time set up...
3565 bool leftMat = builder.isMatrix(left);
3566 bool rightMat = builder.isMatrix(right);
3567 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3568 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3569 spv::Id scalarType = builder.getScalarTypeId(typeId);
3570 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3571 std::vector<spv::Id> results;
3572 spv::Id smearVec = spv::NoResult;
3573 if (builder.isScalar(left))
3574 smearVec = builder.smearScalar(precision, left, vecType);
3575 else if (builder.isScalar(right))
3576 smearVec = builder.smearScalar(precision, right, vecType);
3577
3578 // do each vector op
3579 for (unsigned int c = 0; c < numCols; ++c) {
3580 std::vector<unsigned int> indexes;
3581 indexes.push_back(c);
3582 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3583 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003584 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3585 addDecoration(result, noContraction);
3586 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003587 }
3588
3589 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003590 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003591 }
3592 default:
3593 assert(0);
3594 return spv::NoResult;
3595 }
3596}
3597
qining25262b32016-05-06 17:25:16 -04003598spv::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 -06003599{
3600 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003601 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003603 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003604#ifdef AMD_EXTENSIONS
3605 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3606#else
Rex Xu04db3f52015-09-16 11:44:02 +08003607 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003608#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003609
3610 switch (op) {
3611 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003612 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003613 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003614 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003615 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003616 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003617 unaryOp = spv::OpSNegate;
3618 break;
3619
3620 case glslang::EOpLogicalNot:
3621 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003622 unaryOp = spv::OpLogicalNot;
3623 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003624 case glslang::EOpBitwiseNot:
3625 unaryOp = spv::OpNot;
3626 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003627
John Kessenich140f3df2015-06-26 16:58:36 -06003628 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003630 break;
3631 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003632 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 break;
3634 case glslang::EOpTranspose:
3635 unaryOp = spv::OpTranspose;
3636 break;
3637
3638 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
3644 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003645 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003646 break;
3647 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003648 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003649 break;
3650 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003651 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003652 break;
3653 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003654 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
3656 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003657 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 break;
3659 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003661 break;
3662
3663 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003664 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003665 break;
3666 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003667 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003668 break;
3669 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003670 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003671 break;
3672 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003674 break;
3675 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003677 break;
3678 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003679 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681
3682 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003683 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003684 break;
3685 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003686 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688
3689 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003691 break;
3692 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707
3708 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003709 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 break;
3726
3727 case glslang::EOpIsNan:
3728 unaryOp = spv::OpIsNan;
3729 break;
3730 case glslang::EOpIsInf:
3731 unaryOp = spv::OpIsInf;
3732 break;
LoopDawg592860c2016-06-09 08:57:35 -06003733 case glslang::EOpIsFinite:
3734 unaryOp = spv::OpIsFinite;
3735 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003736
Rex Xucbc426e2015-12-15 16:03:10 +08003737 case glslang::EOpFloatBitsToInt:
3738 case glslang::EOpFloatBitsToUint:
3739 case glslang::EOpIntBitsToFloat:
3740 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003741 case glslang::EOpDoubleBitsToInt64:
3742 case glslang::EOpDoubleBitsToUint64:
3743 case glslang::EOpInt64BitsToDouble:
3744 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003745 unaryOp = spv::OpBitcast;
3746 break;
3747
John Kessenich140f3df2015-06-26 16:58:36 -06003748 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003749 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003750 break;
3751 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003752 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003766 case glslang::EOpPackSnorm4x8:
3767 libCall = spv::GLSLstd450PackSnorm4x8;
3768 break;
3769 case glslang::EOpUnpackSnorm4x8:
3770 libCall = spv::GLSLstd450UnpackSnorm4x8;
3771 break;
3772 case glslang::EOpPackUnorm4x8:
3773 libCall = spv::GLSLstd450PackUnorm4x8;
3774 break;
3775 case glslang::EOpUnpackUnorm4x8:
3776 libCall = spv::GLSLstd450UnpackUnorm4x8;
3777 break;
3778 case glslang::EOpPackDouble2x32:
3779 libCall = spv::GLSLstd450PackDouble2x32;
3780 break;
3781 case glslang::EOpUnpackDouble2x32:
3782 libCall = spv::GLSLstd450UnpackDouble2x32;
3783 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003784
Rex Xu8ff43de2016-04-22 16:51:45 +08003785 case glslang::EOpPackInt2x32:
3786 case glslang::EOpUnpackInt2x32:
3787 case glslang::EOpPackUint2x32:
3788 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003789 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003790 break;
3791
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003792#ifdef AMD_EXTENSIONS
3793 case glslang::EOpPackFloat2x16:
3794 case glslang::EOpUnpackFloat2x16:
3795 unaryOp = spv::OpBitcast;
3796 break;
3797#endif
3798
John Kessenich140f3df2015-06-26 16:58:36 -06003799 case glslang::EOpDPdx:
3800 unaryOp = spv::OpDPdx;
3801 break;
3802 case glslang::EOpDPdy:
3803 unaryOp = spv::OpDPdy;
3804 break;
3805 case glslang::EOpFwidth:
3806 unaryOp = spv::OpFwidth;
3807 break;
3808 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003809 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003810 unaryOp = spv::OpDPdxFine;
3811 break;
3812 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003813 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003814 unaryOp = spv::OpDPdyFine;
3815 break;
3816 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003817 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003818 unaryOp = spv::OpFwidthFine;
3819 break;
3820 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003821 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003822 unaryOp = spv::OpDPdxCoarse;
3823 break;
3824 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003825 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003826 unaryOp = spv::OpDPdyCoarse;
3827 break;
3828 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003829 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003830 unaryOp = spv::OpFwidthCoarse;
3831 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003832 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003833 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003834 libCall = spv::GLSLstd450InterpolateAtCentroid;
3835 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 case glslang::EOpAny:
3837 unaryOp = spv::OpAny;
3838 break;
3839 case glslang::EOpAll:
3840 unaryOp = spv::OpAll;
3841 break;
3842
3843 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 if (isFloat)
3845 libCall = spv::GLSLstd450FAbs;
3846 else
3847 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003848 break;
3849 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 if (isFloat)
3851 libCall = spv::GLSLstd450FSign;
3852 else
3853 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003854 break;
3855
John Kessenichfc51d282015-08-19 13:34:18 -06003856 case glslang::EOpAtomicCounterIncrement:
3857 case glslang::EOpAtomicCounterDecrement:
3858 case glslang::EOpAtomicCounter:
3859 {
3860 // Handle all of the atomics in one place, in createAtomicOperation()
3861 std::vector<spv::Id> operands;
3862 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003863 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003864 }
3865
John Kessenichfc51d282015-08-19 13:34:18 -06003866 case glslang::EOpBitFieldReverse:
3867 unaryOp = spv::OpBitReverse;
3868 break;
3869 case glslang::EOpBitCount:
3870 unaryOp = spv::OpBitCount;
3871 break;
3872 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003873 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003874 break;
3875 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003876 if (isUnsigned)
3877 libCall = spv::GLSLstd450FindUMsb;
3878 else
3879 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003880 break;
3881
Rex Xu574ab042016-04-14 16:53:07 +08003882 case glslang::EOpBallot:
3883 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003884 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003885 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003886 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003887#ifdef AMD_EXTENSIONS
3888 case glslang::EOpMinInvocations:
3889 case glslang::EOpMaxInvocations:
3890 case glslang::EOpAddInvocations:
3891 case glslang::EOpMinInvocationsNonUniform:
3892 case glslang::EOpMaxInvocationsNonUniform:
3893 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003894 case glslang::EOpMinInvocationsInclusiveScan:
3895 case glslang::EOpMaxInvocationsInclusiveScan:
3896 case glslang::EOpAddInvocationsInclusiveScan:
3897 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3898 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3899 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3900 case glslang::EOpMinInvocationsExclusiveScan:
3901 case glslang::EOpMaxInvocationsExclusiveScan:
3902 case glslang::EOpAddInvocationsExclusiveScan:
3903 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3904 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3905 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003906#endif
Rex Xu51596642016-09-21 18:56:12 +08003907 {
3908 std::vector<spv::Id> operands;
3909 operands.push_back(operand);
3910 return createInvocationsOperation(op, typeId, operands, typeProxy);
3911 }
Rex Xu9d93a232016-05-05 12:30:44 +08003912
3913#ifdef AMD_EXTENSIONS
3914 case glslang::EOpMbcnt:
3915 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3916 libCall = spv::MbcntAMD;
3917 break;
3918
3919 case glslang::EOpCubeFaceIndex:
3920 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3921 libCall = spv::CubeFaceIndexAMD;
3922 break;
3923
3924 case glslang::EOpCubeFaceCoord:
3925 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3926 libCall = spv::CubeFaceCoordAMD;
3927 break;
3928#endif
Rex Xu338b1852016-05-05 20:38:33 +08003929
John Kessenich140f3df2015-06-26 16:58:36 -06003930 default:
3931 return 0;
3932 }
3933
3934 spv::Id id;
3935 if (libCall >= 0) {
3936 std::vector<spv::Id> args;
3937 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003938 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003939 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003940 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003941 }
John Kessenich140f3df2015-06-26 16:58:36 -06003942
qining25262b32016-05-06 17:25:16 -04003943 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003944 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003945}
3946
John Kessenich7a53f762016-01-20 11:19:27 -07003947// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003948spv::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 -07003949{
3950 // Handle unary operations vector by vector.
3951 // The result type is the same type as the original type.
3952 // The algorithm is to:
3953 // - break the matrix into vectors
3954 // - apply the operation to each vector
3955 // - make a matrix out the vector results
3956
3957 // get the types sorted out
3958 int numCols = builder.getNumColumns(operand);
3959 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003960 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3961 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003962 std::vector<spv::Id> results;
3963
3964 // do each vector op
3965 for (int c = 0; c < numCols; ++c) {
3966 std::vector<unsigned int> indexes;
3967 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003968 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3969 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3970 addDecoration(destVec, noContraction);
3971 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003972 }
3973
3974 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003975 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003976}
3977
Rex Xu73e3ce72016-04-27 18:48:17 +08003978spv::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 -06003979{
3980 spv::Op convOp = spv::OpNop;
3981 spv::Id zero = 0;
3982 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003983 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003984
3985 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3986
3987 switch (op) {
3988 case glslang::EOpConvIntToBool:
3989 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003990 case glslang::EOpConvInt64ToBool:
3991 case glslang::EOpConvUint64ToBool:
3992 zero = (op == glslang::EOpConvInt64ToBool ||
3993 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003994 zero = makeSmearedConstant(zero, vectorSize);
3995 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3996
3997 case glslang::EOpConvFloatToBool:
3998 zero = builder.makeFloatConstant(0.0F);
3999 zero = makeSmearedConstant(zero, vectorSize);
4000 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4001
4002 case glslang::EOpConvDoubleToBool:
4003 zero = builder.makeDoubleConstant(0.0);
4004 zero = makeSmearedConstant(zero, vectorSize);
4005 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4006
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004007#ifdef AMD_EXTENSIONS
4008 case glslang::EOpConvFloat16ToBool:
4009 zero = builder.makeFloat16Constant(0.0F);
4010 zero = makeSmearedConstant(zero, vectorSize);
4011 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4012#endif
4013
John Kessenich140f3df2015-06-26 16:58:36 -06004014 case glslang::EOpConvBoolToFloat:
4015 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004016 zero = builder.makeFloatConstant(0.0F);
4017 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004018 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004019
John Kessenich140f3df2015-06-26 16:58:36 -06004020 case glslang::EOpConvBoolToDouble:
4021 convOp = spv::OpSelect;
4022 zero = builder.makeDoubleConstant(0.0);
4023 one = builder.makeDoubleConstant(1.0);
4024 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004025
4026#ifdef AMD_EXTENSIONS
4027 case glslang::EOpConvBoolToFloat16:
4028 convOp = spv::OpSelect;
4029 zero = builder.makeFloat16Constant(0.0F);
4030 one = builder.makeFloat16Constant(1.0F);
4031 break;
4032#endif
4033
John Kessenich140f3df2015-06-26 16:58:36 -06004034 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004035 case glslang::EOpConvBoolToInt64:
4036 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4037 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004038 convOp = spv::OpSelect;
4039 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004040
John Kessenich140f3df2015-06-26 16:58:36 -06004041 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004042 case glslang::EOpConvBoolToUint64:
4043 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4044 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004045 convOp = spv::OpSelect;
4046 break;
4047
4048 case glslang::EOpConvIntToFloat:
4049 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004050 case glslang::EOpConvInt64ToFloat:
4051 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004052#ifdef AMD_EXTENSIONS
4053 case glslang::EOpConvIntToFloat16:
4054 case glslang::EOpConvInt64ToFloat16:
4055#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004056 convOp = spv::OpConvertSToF;
4057 break;
4058
4059 case glslang::EOpConvUintToFloat:
4060 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004061 case glslang::EOpConvUint64ToFloat:
4062 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004063#ifdef AMD_EXTENSIONS
4064 case glslang::EOpConvUintToFloat16:
4065 case glslang::EOpConvUint64ToFloat16:
4066#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004067 convOp = spv::OpConvertUToF;
4068 break;
4069
4070 case glslang::EOpConvDoubleToFloat:
4071 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004072#ifdef AMD_EXTENSIONS
4073 case glslang::EOpConvDoubleToFloat16:
4074 case glslang::EOpConvFloat16ToDouble:
4075 case glslang::EOpConvFloatToFloat16:
4076 case glslang::EOpConvFloat16ToFloat:
4077#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004078 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004079 if (builder.isMatrixType(destType))
4080 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082
4083 case glslang::EOpConvFloatToInt:
4084 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004085 case glslang::EOpConvFloatToInt64:
4086 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004087#ifdef AMD_EXTENSIONS
4088 case glslang::EOpConvFloat16ToInt:
4089 case glslang::EOpConvFloat16ToInt64:
4090#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004091 convOp = spv::OpConvertFToS;
4092 break;
4093
4094 case glslang::EOpConvUintToInt:
4095 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004096 case glslang::EOpConvUint64ToInt64:
4097 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004098 if (builder.isInSpecConstCodeGenMode()) {
4099 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004100 zero = (op == glslang::EOpConvUint64ToInt64 ||
4101 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004102 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004103 // Use OpIAdd, instead of OpBitcast to do the conversion when
4104 // generating for OpSpecConstantOp instruction.
4105 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4106 }
4107 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004108 convOp = spv::OpBitcast;
4109 break;
4110
4111 case glslang::EOpConvFloatToUint:
4112 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004113 case glslang::EOpConvFloatToUint64:
4114 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004115#ifdef AMD_EXTENSIONS
4116 case glslang::EOpConvFloat16ToUint:
4117 case glslang::EOpConvFloat16ToUint64:
4118#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004119 convOp = spv::OpConvertFToU;
4120 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004121
4122 case glslang::EOpConvIntToInt64:
4123 case glslang::EOpConvInt64ToInt:
4124 convOp = spv::OpSConvert;
4125 break;
4126
4127 case glslang::EOpConvUintToUint64:
4128 case glslang::EOpConvUint64ToUint:
4129 convOp = spv::OpUConvert;
4130 break;
4131
4132 case glslang::EOpConvIntToUint64:
4133 case glslang::EOpConvInt64ToUint:
4134 case glslang::EOpConvUint64ToInt:
4135 case glslang::EOpConvUintToInt64:
4136 // OpSConvert/OpUConvert + OpBitCast
4137 switch (op) {
4138 case glslang::EOpConvIntToUint64:
4139 convOp = spv::OpSConvert;
4140 type = builder.makeIntType(64);
4141 break;
4142 case glslang::EOpConvInt64ToUint:
4143 convOp = spv::OpSConvert;
4144 type = builder.makeIntType(32);
4145 break;
4146 case glslang::EOpConvUint64ToInt:
4147 convOp = spv::OpUConvert;
4148 type = builder.makeUintType(32);
4149 break;
4150 case glslang::EOpConvUintToInt64:
4151 convOp = spv::OpUConvert;
4152 type = builder.makeUintType(64);
4153 break;
4154 default:
4155 assert(0);
4156 break;
4157 }
4158
4159 if (vectorSize > 0)
4160 type = builder.makeVectorType(type, vectorSize);
4161
4162 operand = builder.createUnaryOp(convOp, type, operand);
4163
4164 if (builder.isInSpecConstCodeGenMode()) {
4165 // Build zero scalar or vector for OpIAdd.
4166 zero = (op == glslang::EOpConvIntToUint64 ||
4167 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4168 zero = makeSmearedConstant(zero, vectorSize);
4169 // Use OpIAdd, instead of OpBitcast to do the conversion when
4170 // generating for OpSpecConstantOp instruction.
4171 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4172 }
4173 // For normal run-time conversion instruction, use OpBitcast.
4174 convOp = spv::OpBitcast;
4175 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 default:
4177 break;
4178 }
4179
4180 spv::Id result = 0;
4181 if (convOp == spv::OpNop)
4182 return result;
4183
4184 if (convOp == spv::OpSelect) {
4185 zero = makeSmearedConstant(zero, vectorSize);
4186 one = makeSmearedConstant(one, vectorSize);
4187 result = builder.createTriOp(convOp, destType, operand, one, zero);
4188 } else
4189 result = builder.createUnaryOp(convOp, destType, operand);
4190
John Kessenich32cfd492016-02-02 12:37:46 -07004191 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004192}
4193
4194spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4195{
4196 if (vectorSize == 0)
4197 return constant;
4198
4199 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4200 std::vector<spv::Id> components;
4201 for (int c = 0; c < vectorSize; ++c)
4202 components.push_back(constant);
4203 return builder.makeCompositeConstant(vectorTypeId, components);
4204}
4205
John Kessenich426394d2015-07-23 10:22:48 -06004206// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004207spv::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 -06004208{
4209 spv::Op opCode = spv::OpNop;
4210
4211 switch (op) {
4212 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004213 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004214 opCode = spv::OpAtomicIAdd;
4215 break;
4216 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004217 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004218 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004219 break;
4220 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004221 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004222 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004223 break;
4224 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004225 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004226 opCode = spv::OpAtomicAnd;
4227 break;
4228 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004229 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004230 opCode = spv::OpAtomicOr;
4231 break;
4232 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004233 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004234 opCode = spv::OpAtomicXor;
4235 break;
4236 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004237 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004238 opCode = spv::OpAtomicExchange;
4239 break;
4240 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004241 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004242 opCode = spv::OpAtomicCompareExchange;
4243 break;
4244 case glslang::EOpAtomicCounterIncrement:
4245 opCode = spv::OpAtomicIIncrement;
4246 break;
4247 case glslang::EOpAtomicCounterDecrement:
4248 opCode = spv::OpAtomicIDecrement;
4249 break;
4250 case glslang::EOpAtomicCounter:
4251 opCode = spv::OpAtomicLoad;
4252 break;
4253 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004254 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004255 break;
4256 }
4257
4258 // Sort out the operands
4259 // - mapping from glslang -> SPV
4260 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004261 // - compare-exchange swaps the value and comparator
4262 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004263 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4264 auto opIt = operands.begin(); // walk the glslang operands
4265 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004266 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4267 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4268 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004269 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4270 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004271 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004272 spvAtomicOperands.push_back(*(opIt + 1));
4273 spvAtomicOperands.push_back(*opIt);
4274 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004275 }
John Kessenich426394d2015-07-23 10:22:48 -06004276
John Kessenich3e60a6f2015-09-14 22:45:16 -06004277 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004278 for (; opIt != operands.end(); ++opIt)
4279 spvAtomicOperands.push_back(*opIt);
4280
4281 return builder.createOp(opCode, typeId, spvAtomicOperands);
4282}
4283
John Kessenich91cef522016-05-05 16:45:40 -06004284// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004285spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004286{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004287#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004288 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004289 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004290#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004291
Rex Xu51596642016-09-21 18:56:12 +08004292 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004293 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004294 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4295
chaocf200da82016-12-20 12:44:35 -08004296 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4297 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004298 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4299 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004300 } else if (op == glslang::EOpAnyInvocation ||
4301 op == glslang::EOpAllInvocations ||
4302 op == glslang::EOpAllInvocationsEqual) {
4303 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4304 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004305 } else {
4306 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004307#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004308 if (op == glslang::EOpMinInvocationsNonUniform ||
4309 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004310 op == glslang::EOpAddInvocationsNonUniform ||
4311 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4312 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4313 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4314 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4315 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4316 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004317 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004318#endif
Rex Xu51596642016-09-21 18:56:12 +08004319
4320 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004321#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004322 switch (op) {
4323 case glslang::EOpMinInvocations:
4324 case glslang::EOpMaxInvocations:
4325 case glslang::EOpAddInvocations:
4326 case glslang::EOpMinInvocationsNonUniform:
4327 case glslang::EOpMaxInvocationsNonUniform:
4328 case glslang::EOpAddInvocationsNonUniform:
4329 groupOperation = spv::GroupOperationReduce;
4330 spvGroupOperands.push_back(groupOperation);
4331 break;
4332 case glslang::EOpMinInvocationsInclusiveScan:
4333 case glslang::EOpMaxInvocationsInclusiveScan:
4334 case glslang::EOpAddInvocationsInclusiveScan:
4335 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4336 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4337 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4338 groupOperation = spv::GroupOperationInclusiveScan;
4339 spvGroupOperands.push_back(groupOperation);
4340 break;
4341 case glslang::EOpMinInvocationsExclusiveScan:
4342 case glslang::EOpMaxInvocationsExclusiveScan:
4343 case glslang::EOpAddInvocationsExclusiveScan:
4344 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4345 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4346 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4347 groupOperation = spv::GroupOperationExclusiveScan;
4348 spvGroupOperands.push_back(groupOperation);
4349 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004350 default:
4351 break;
Rex Xu430ef402016-10-14 17:22:23 +08004352 }
Rex Xu9d93a232016-05-05 12:30:44 +08004353#endif
Rex Xu51596642016-09-21 18:56:12 +08004354 }
4355
4356 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4357 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004358
4359 switch (op) {
4360 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004361 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004362 break;
John Kessenich91cef522016-05-05 16:45:40 -06004363 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004364 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004365 break;
John Kessenich91cef522016-05-05 16:45:40 -06004366 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004367 opCode = spv::OpSubgroupAllEqualKHR;
4368 break;
Rex Xu51596642016-09-21 18:56:12 +08004369 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004370 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004371 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004372 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004373 break;
4374 case glslang::EOpReadFirstInvocation:
4375 opCode = spv::OpSubgroupFirstInvocationKHR;
4376 break;
4377 case glslang::EOpBallot:
4378 {
4379 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4380 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4381 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4382 //
4383 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4384 //
4385 spv::Id uintType = builder.makeUintType(32);
4386 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4387 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4388
4389 std::vector<spv::Id> components;
4390 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4391 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4392
4393 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4394 return builder.createUnaryOp(spv::OpBitcast, typeId,
4395 builder.createCompositeConstruct(uvec2Type, components));
4396 }
4397
Rex Xu9d93a232016-05-05 12:30:44 +08004398#ifdef AMD_EXTENSIONS
4399 case glslang::EOpMinInvocations:
4400 case glslang::EOpMaxInvocations:
4401 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004402 case glslang::EOpMinInvocationsInclusiveScan:
4403 case glslang::EOpMaxInvocationsInclusiveScan:
4404 case glslang::EOpAddInvocationsInclusiveScan:
4405 case glslang::EOpMinInvocationsExclusiveScan:
4406 case glslang::EOpMaxInvocationsExclusiveScan:
4407 case glslang::EOpAddInvocationsExclusiveScan:
4408 if (op == glslang::EOpMinInvocations ||
4409 op == glslang::EOpMinInvocationsInclusiveScan ||
4410 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004411 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004412 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004413 else {
4414 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004415 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004416 else
Rex Xu51596642016-09-21 18:56:12 +08004417 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004418 }
Rex Xu430ef402016-10-14 17:22:23 +08004419 } else if (op == glslang::EOpMaxInvocations ||
4420 op == glslang::EOpMaxInvocationsInclusiveScan ||
4421 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004422 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004423 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004424 else {
4425 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004426 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004427 else
Rex Xu51596642016-09-21 18:56:12 +08004428 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004429 }
4430 } else {
4431 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004432 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004433 else
Rex Xu51596642016-09-21 18:56:12 +08004434 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004435 }
4436
Rex Xu2bbbe062016-08-23 15:41:05 +08004437 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004438 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004439
4440 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004441 case glslang::EOpMinInvocationsNonUniform:
4442 case glslang::EOpMaxInvocationsNonUniform:
4443 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004444 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4445 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4446 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4447 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4448 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4449 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4450 if (op == glslang::EOpMinInvocationsNonUniform ||
4451 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4452 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004453 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004454 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004455 else {
4456 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004457 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004458 else
Rex Xu51596642016-09-21 18:56:12 +08004459 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004460 }
4461 }
Rex Xu430ef402016-10-14 17:22:23 +08004462 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4463 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4464 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004465 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004466 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004467 else {
4468 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004469 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004470 else
Rex Xu51596642016-09-21 18:56:12 +08004471 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004472 }
4473 }
4474 else {
4475 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004476 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004477 else
Rex Xu51596642016-09-21 18:56:12 +08004478 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004479 }
4480
Rex Xu2bbbe062016-08-23 15:41:05 +08004481 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004482 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004483
4484 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004485#endif
John Kessenich91cef522016-05-05 16:45:40 -06004486 default:
4487 logger->missingFunctionality("invocation operation");
4488 return spv::NoResult;
4489 }
Rex Xu51596642016-09-21 18:56:12 +08004490
4491 assert(opCode != spv::OpNop);
4492 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004493}
4494
Rex Xu2bbbe062016-08-23 15:41:05 +08004495// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004496spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004497{
Rex Xub7072052016-09-26 15:53:40 +08004498#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004499 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4500 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004501 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004502 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004503 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4504 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4505 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004506#else
4507 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4508 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004509 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4510 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004511#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004512
4513 // Handle group invocation operations scalar by scalar.
4514 // The result type is the same type as the original type.
4515 // The algorithm is to:
4516 // - break the vector into scalars
4517 // - apply the operation to each scalar
4518 // - make a vector out the scalar results
4519
4520 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004521 int numComponents = builder.getNumComponents(operands[0]);
4522 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004523 std::vector<spv::Id> results;
4524
4525 // do each scalar op
4526 for (int comp = 0; comp < numComponents; ++comp) {
4527 std::vector<unsigned int> indexes;
4528 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004529 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004530 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004531 if (op == spv::OpSubgroupReadInvocationKHR) {
4532 spvGroupOperands.push_back(scalar);
4533 spvGroupOperands.push_back(operands[1]);
4534 } else if (op == spv::OpGroupBroadcast) {
4535 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004536 spvGroupOperands.push_back(scalar);
4537 spvGroupOperands.push_back(operands[1]);
4538 } else {
chaocf200da82016-12-20 12:44:35 -08004539 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004540 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004541 spvGroupOperands.push_back(scalar);
4542 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004543
Rex Xub7072052016-09-26 15:53:40 +08004544 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004545 }
4546
4547 // put the pieces together
4548 return builder.createCompositeConstruct(typeId, results);
4549}
Rex Xu2bbbe062016-08-23 15:41:05 +08004550
John Kessenich5e4b1242015-08-06 22:53:06 -06004551spv::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 -06004552{
Rex Xu8ff43de2016-04-22 16:51:45 +08004553 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004554#ifdef AMD_EXTENSIONS
4555 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4556#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004557 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004558#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004559
John Kessenich140f3df2015-06-26 16:58:36 -06004560 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004561 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004562 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004563 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004564 spv::Id typeId0 = 0;
4565 if (consumedOperands > 0)
4566 typeId0 = builder.getTypeId(operands[0]);
4567 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004568
4569 switch (op) {
4570 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004571 if (isFloat)
4572 libCall = spv::GLSLstd450FMin;
4573 else if (isUnsigned)
4574 libCall = spv::GLSLstd450UMin;
4575 else
4576 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004577 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004578 break;
4579 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004580 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004581 break;
4582 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004583 if (isFloat)
4584 libCall = spv::GLSLstd450FMax;
4585 else if (isUnsigned)
4586 libCall = spv::GLSLstd450UMax;
4587 else
4588 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004589 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004590 break;
4591 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004592 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004593 break;
4594 case glslang::EOpDot:
4595 opCode = spv::OpDot;
4596 break;
4597 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004598 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004599 break;
4600
4601 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004602 if (isFloat)
4603 libCall = spv::GLSLstd450FClamp;
4604 else if (isUnsigned)
4605 libCall = spv::GLSLstd450UClamp;
4606 else
4607 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004608 builder.promoteScalar(precision, operands.front(), operands[1]);
4609 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004610 break;
4611 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004612 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4613 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004614 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004615 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004616 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004617 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004618 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004619 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004620 break;
4621 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004622 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004623 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004624 break;
4625 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004626 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004627 builder.promoteScalar(precision, operands[0], operands[2]);
4628 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004629 break;
4630
4631 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004632 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004633 break;
4634 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004635 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004636 break;
4637 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004638 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004639 break;
4640 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004641 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004642 break;
4643 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004644 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004645 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004646 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004647 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004648 libCall = spv::GLSLstd450InterpolateAtSample;
4649 break;
4650 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004651 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004652 libCall = spv::GLSLstd450InterpolateAtOffset;
4653 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004654 case glslang::EOpAddCarry:
4655 opCode = spv::OpIAddCarry;
4656 typeId = builder.makeStructResultType(typeId0, typeId0);
4657 consumedOperands = 2;
4658 break;
4659 case glslang::EOpSubBorrow:
4660 opCode = spv::OpISubBorrow;
4661 typeId = builder.makeStructResultType(typeId0, typeId0);
4662 consumedOperands = 2;
4663 break;
4664 case glslang::EOpUMulExtended:
4665 opCode = spv::OpUMulExtended;
4666 typeId = builder.makeStructResultType(typeId0, typeId0);
4667 consumedOperands = 2;
4668 break;
4669 case glslang::EOpIMulExtended:
4670 opCode = spv::OpSMulExtended;
4671 typeId = builder.makeStructResultType(typeId0, typeId0);
4672 consumedOperands = 2;
4673 break;
4674 case glslang::EOpBitfieldExtract:
4675 if (isUnsigned)
4676 opCode = spv::OpBitFieldUExtract;
4677 else
4678 opCode = spv::OpBitFieldSExtract;
4679 break;
4680 case glslang::EOpBitfieldInsert:
4681 opCode = spv::OpBitFieldInsert;
4682 break;
4683
4684 case glslang::EOpFma:
4685 libCall = spv::GLSLstd450Fma;
4686 break;
4687 case glslang::EOpFrexp:
4688 libCall = spv::GLSLstd450FrexpStruct;
4689 if (builder.getNumComponents(operands[0]) == 1)
4690 frexpIntType = builder.makeIntegerType(32, true);
4691 else
4692 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4693 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4694 consumedOperands = 1;
4695 break;
4696 case glslang::EOpLdexp:
4697 libCall = spv::GLSLstd450Ldexp;
4698 break;
4699
Rex Xu574ab042016-04-14 16:53:07 +08004700 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004701 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004702
Rex Xu9d93a232016-05-05 12:30:44 +08004703#ifdef AMD_EXTENSIONS
4704 case glslang::EOpSwizzleInvocations:
4705 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4706 libCall = spv::SwizzleInvocationsAMD;
4707 break;
4708 case glslang::EOpSwizzleInvocationsMasked:
4709 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4710 libCall = spv::SwizzleInvocationsMaskedAMD;
4711 break;
4712 case glslang::EOpWriteInvocation:
4713 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4714 libCall = spv::WriteInvocationAMD;
4715 break;
4716
4717 case glslang::EOpMin3:
4718 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4719 if (isFloat)
4720 libCall = spv::FMin3AMD;
4721 else {
4722 if (isUnsigned)
4723 libCall = spv::UMin3AMD;
4724 else
4725 libCall = spv::SMin3AMD;
4726 }
4727 break;
4728 case glslang::EOpMax3:
4729 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4730 if (isFloat)
4731 libCall = spv::FMax3AMD;
4732 else {
4733 if (isUnsigned)
4734 libCall = spv::UMax3AMD;
4735 else
4736 libCall = spv::SMax3AMD;
4737 }
4738 break;
4739 case glslang::EOpMid3:
4740 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4741 if (isFloat)
4742 libCall = spv::FMid3AMD;
4743 else {
4744 if (isUnsigned)
4745 libCall = spv::UMid3AMD;
4746 else
4747 libCall = spv::SMid3AMD;
4748 }
4749 break;
4750
4751 case glslang::EOpInterpolateAtVertex:
4752 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4753 libCall = spv::InterpolateAtVertexAMD;
4754 break;
4755#endif
4756
John Kessenich140f3df2015-06-26 16:58:36 -06004757 default:
4758 return 0;
4759 }
4760
4761 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004762 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004763 // Use an extended instruction from the standard library.
4764 // Construct the call arguments, without modifying the original operands vector.
4765 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4766 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004767 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004768 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004769 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004770 case 0:
4771 // should all be handled by visitAggregate and createNoArgOperation
4772 assert(0);
4773 return 0;
4774 case 1:
4775 // should all be handled by createUnaryOperation
4776 assert(0);
4777 return 0;
4778 case 2:
4779 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4780 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004781 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004782 // anything 3 or over doesn't have l-value operands, so all should be consumed
4783 assert(consumedOperands == operands.size());
4784 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004785 break;
4786 }
4787 }
4788
John Kessenich55e7d112015-11-15 21:33:39 -07004789 // Decode the return types that were structures
4790 switch (op) {
4791 case glslang::EOpAddCarry:
4792 case glslang::EOpSubBorrow:
4793 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4794 id = builder.createCompositeExtract(id, typeId0, 0);
4795 break;
4796 case glslang::EOpUMulExtended:
4797 case glslang::EOpIMulExtended:
4798 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4799 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4800 break;
4801 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004802 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004803 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4804 id = builder.createCompositeExtract(id, typeId0, 0);
4805 break;
4806 default:
4807 break;
4808 }
4809
John Kessenich32cfd492016-02-02 12:37:46 -07004810 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004811}
4812
Rex Xu9d93a232016-05-05 12:30:44 +08004813// Intrinsics with no arguments (or no return value, and no precision).
4814spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004815{
4816 // TODO: get the barrier operands correct
4817
4818 switch (op) {
4819 case glslang::EOpEmitVertex:
4820 builder.createNoResultOp(spv::OpEmitVertex);
4821 return 0;
4822 case glslang::EOpEndPrimitive:
4823 builder.createNoResultOp(spv::OpEndPrimitive);
4824 return 0;
4825 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004826 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004827 return 0;
4828 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004829 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004830 return 0;
4831 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004832 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004833 return 0;
4834 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004835 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004836 return 0;
4837 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004838 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004839 return 0;
4840 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004841 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004842 return 0;
4843 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004844 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004845 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004846 case glslang::EOpAllMemoryBarrierWithGroupSync:
4847 // Control barrier with non-"None" semantic is also a memory barrier.
4848 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4849 return 0;
4850 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4851 // Control barrier with non-"None" semantic is also a memory barrier.
4852 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4853 return 0;
4854 case glslang::EOpWorkgroupMemoryBarrier:
4855 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4856 return 0;
4857 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4858 // Control barrier with non-"None" semantic is also a memory barrier.
4859 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4860 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004861#ifdef AMD_EXTENSIONS
4862 case glslang::EOpTime:
4863 {
4864 std::vector<spv::Id> args; // Dummy arguments
4865 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4866 return builder.setPrecision(id, precision);
4867 }
4868#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004869 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004870 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004871 return 0;
4872 }
4873}
4874
4875spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4876{
John Kessenich2f273362015-07-18 22:34:27 -06004877 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004878 spv::Id id;
4879 if (symbolValues.end() != iter) {
4880 id = iter->second;
4881 return id;
4882 }
4883
4884 // it was not found, create it
4885 id = createSpvVariable(symbol);
4886 symbolValues[symbol->getId()] = id;
4887
Rex Xuc884b4a2016-06-29 15:03:44 +08004888 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004889 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004890 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004891 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004892 if (symbol->getType().getQualifier().hasSpecConstantId())
4893 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004894 if (symbol->getQualifier().hasIndex())
4895 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4896 if (symbol->getQualifier().hasComponent())
4897 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4898 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004899 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004900 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004901 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004902 if (symbol->getQualifier().hasXfbBuffer())
4903 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4904 if (symbol->getQualifier().hasXfbOffset())
4905 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4906 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004907 // atomic counters use this:
4908 if (symbol->getQualifier().hasOffset())
4909 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004910 }
4911
scygan2c864272016-05-18 18:09:17 +02004912 if (symbol->getQualifier().hasLocation())
4913 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004914 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004915 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004916 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004917 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004918 }
John Kessenich140f3df2015-06-26 16:58:36 -06004919 if (symbol->getQualifier().hasSet())
4920 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004921 else if (IsDescriptorResource(symbol->getType())) {
4922 // default to 0
4923 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4924 }
John Kessenich140f3df2015-06-26 16:58:36 -06004925 if (symbol->getQualifier().hasBinding())
4926 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004927 if (symbol->getQualifier().hasAttachment())
4928 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004929 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004930 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004931 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004932 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004933 if (symbol->getQualifier().hasXfbBuffer())
4934 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4935 }
4936
Rex Xu1da878f2016-02-21 20:59:01 +08004937 if (symbol->getType().isImage()) {
4938 std::vector<spv::Decoration> memory;
4939 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4940 for (unsigned int i = 0; i < memory.size(); ++i)
4941 addDecoration(id, memory[i]);
4942 }
4943
John Kessenich140f3df2015-06-26 16:58:36 -06004944 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004945 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004946 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004947 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004948
John Kessenichecba76f2017-01-06 00:34:48 -07004949#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004950 if (builtIn == spv::BuiltInSampleMask) {
4951 spv::Decoration decoration;
4952 // GL_NV_sample_mask_override_coverage extension
4953 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004954 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004955 else
4956 decoration = (spv::Decoration)spv::DecorationMax;
4957 addDecoration(id, decoration);
4958 if (decoration != spv::DecorationMax) {
4959 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4960 }
4961 }
chaoc771d89f2017-01-13 01:10:53 -08004962 else if (builtIn == spv::BuiltInLayer) {
4963 // SPV_NV_viewport_array2 extension
4964 if (symbol->getQualifier().layoutViewportRelative)
4965 {
4966 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4967 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4968 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4969 }
4970 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4971 {
4972 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4973 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4974 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4975 }
4976 }
4977
chaoc6e5acae2016-12-20 13:28:52 -08004978 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004979 addDecoration(id, spv::DecorationPassthroughNV);
4980 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004981 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4982 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004983#endif
4984
John Kessenich140f3df2015-06-26 16:58:36 -06004985 return id;
4986}
4987
John Kessenich55e7d112015-11-15 21:33:39 -07004988// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004989void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4990{
John Kessenich4016e382016-07-15 11:53:56 -06004991 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004992 builder.addDecoration(id, dec);
4993}
4994
John Kessenich55e7d112015-11-15 21:33:39 -07004995// If 'dec' is valid, add a one-operand decoration to an object
4996void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4997{
John Kessenich4016e382016-07-15 11:53:56 -06004998 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004999 builder.addDecoration(id, dec, value);
5000}
5001
5002// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005003void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5004{
John Kessenich4016e382016-07-15 11:53:56 -06005005 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005006 builder.addMemberDecoration(id, (unsigned)member, dec);
5007}
5008
John Kessenich92187592016-02-01 13:45:25 -07005009// If 'dec' is valid, add a one-operand decoration to a struct member
5010void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5011{
John Kessenich4016e382016-07-15 11:53:56 -06005012 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005013 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5014}
5015
John Kessenich55e7d112015-11-15 21:33:39 -07005016// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005017// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005018//
5019// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5020//
5021// Recursively walk the nodes. The nodes form a tree whose leaves are
5022// regular constants, which themselves are trees that createSpvConstant()
5023// recursively walks. So, this function walks the "top" of the tree:
5024// - emit specialization constant-building instructions for specConstant
5025// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005026spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005027{
John Kessenich7cc0e282016-03-20 00:46:02 -06005028 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005029
qining4f4bb812016-04-03 23:55:17 -04005030 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005031 if (! node.getQualifier().specConstant) {
5032 // hand off to the non-spec-constant path
5033 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5034 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005035 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005036 nextConst, false);
5037 }
5038
5039 // We now know we have a specialization constant to build
5040
John Kessenichd94c0032016-05-30 19:29:40 -06005041 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005042 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5043 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5044 std::vector<spv::Id> dimConstId;
5045 for (int dim = 0; dim < 3; ++dim) {
5046 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5047 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5048 if (specConst)
5049 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5050 }
5051 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5052 }
5053
5054 // An AST node labelled as specialization constant should be a symbol node.
5055 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5056 if (auto* sn = node.getAsSymbolNode()) {
5057 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005058 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5059 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5060 // will set the builder into spec constant op instruction generating mode.
5061 sub_tree->traverse(this);
5062 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005063 } else if (auto* const_union_array = &sn->getConstArray()){
5064 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005065 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5066 builder.addName(id, sn->getName().c_str());
5067 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005068 }
5069 }
qining4f4bb812016-04-03 23:55:17 -04005070
5071 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5072 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005073 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005074 exit(1);
5075 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005076}
5077
John Kessenich140f3df2015-06-26 16:58:36 -06005078// Use 'consts' as the flattened glslang source of scalar constants to recursively
5079// build the aggregate SPIR-V constant.
5080//
5081// If there are not enough elements present in 'consts', 0 will be substituted;
5082// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5083//
qining08408382016-03-21 09:51:37 -04005084spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005085{
5086 // vector of constants for SPIR-V
5087 std::vector<spv::Id> spvConsts;
5088
5089 // Type is used for struct and array constants
5090 spv::Id typeId = convertGlslangToSpvType(glslangType);
5091
5092 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005093 glslang::TType elementType(glslangType, 0);
5094 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005095 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005096 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005097 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005098 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005099 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005100 } else if (glslangType.getStruct()) {
5101 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5102 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005103 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005104 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005105 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5106 bool zero = nextConst >= consts.size();
5107 switch (glslangType.getBasicType()) {
5108 case glslang::EbtInt:
5109 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5110 break;
5111 case glslang::EbtUint:
5112 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5113 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005114 case glslang::EbtInt64:
5115 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5116 break;
5117 case glslang::EbtUint64:
5118 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5119 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005120 case glslang::EbtFloat:
5121 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5122 break;
5123 case glslang::EbtDouble:
5124 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5125 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005126#ifdef AMD_EXTENSIONS
5127 case glslang::EbtFloat16:
5128 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5129 break;
5130#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005131 case glslang::EbtBool:
5132 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5133 break;
5134 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005135 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005136 break;
5137 }
5138 ++nextConst;
5139 }
5140 } else {
5141 // we have a non-aggregate (scalar) constant
5142 bool zero = nextConst >= consts.size();
5143 spv::Id scalar = 0;
5144 switch (glslangType.getBasicType()) {
5145 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005146 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005147 break;
5148 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005149 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005150 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005151 case glslang::EbtInt64:
5152 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5153 break;
5154 case glslang::EbtUint64:
5155 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5156 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005157 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005158 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005159 break;
5160 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005161 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005162 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005163#ifdef AMD_EXTENSIONS
5164 case glslang::EbtFloat16:
5165 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5166 break;
5167#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005168 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005169 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005170 break;
5171 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005172 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005173 break;
5174 }
5175 ++nextConst;
5176 return scalar;
5177 }
5178
5179 return builder.makeCompositeConstant(typeId, spvConsts);
5180}
5181
John Kessenich7c1aa102015-10-15 13:29:11 -06005182// Return true if the node is a constant or symbol whose reading has no
5183// non-trivial observable cost or effect.
5184bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5185{
5186 // don't know what this is
5187 if (node == nullptr)
5188 return false;
5189
5190 // a constant is safe
5191 if (node->getAsConstantUnion() != nullptr)
5192 return true;
5193
5194 // not a symbol means non-trivial
5195 if (node->getAsSymbolNode() == nullptr)
5196 return false;
5197
5198 // a symbol, depends on what's being read
5199 switch (node->getType().getQualifier().storage) {
5200 case glslang::EvqTemporary:
5201 case glslang::EvqGlobal:
5202 case glslang::EvqIn:
5203 case glslang::EvqInOut:
5204 case glslang::EvqConst:
5205 case glslang::EvqConstReadOnly:
5206 case glslang::EvqUniform:
5207 return true;
5208 default:
5209 return false;
5210 }
qining25262b32016-05-06 17:25:16 -04005211}
John Kessenich7c1aa102015-10-15 13:29:11 -06005212
5213// A node is trivial if it is a single operation with no side effects.
5214// Error on the side of saying non-trivial.
5215// Return true if trivial.
5216bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5217{
5218 if (node == nullptr)
5219 return false;
5220
5221 // symbols and constants are trivial
5222 if (isTrivialLeaf(node))
5223 return true;
5224
5225 // otherwise, it needs to be a simple operation or one or two leaf nodes
5226
5227 // not a simple operation
5228 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5229 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5230 if (binaryNode == nullptr && unaryNode == nullptr)
5231 return false;
5232
5233 // not on leaf nodes
5234 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5235 return false;
5236
5237 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5238 return false;
5239 }
5240
5241 switch (node->getAsOperator()->getOp()) {
5242 case glslang::EOpLogicalNot:
5243 case glslang::EOpConvIntToBool:
5244 case glslang::EOpConvUintToBool:
5245 case glslang::EOpConvFloatToBool:
5246 case glslang::EOpConvDoubleToBool:
5247 case glslang::EOpEqual:
5248 case glslang::EOpNotEqual:
5249 case glslang::EOpLessThan:
5250 case glslang::EOpGreaterThan:
5251 case glslang::EOpLessThanEqual:
5252 case glslang::EOpGreaterThanEqual:
5253 case glslang::EOpIndexDirect:
5254 case glslang::EOpIndexDirectStruct:
5255 case glslang::EOpLogicalXor:
5256 case glslang::EOpAny:
5257 case glslang::EOpAll:
5258 return true;
5259 default:
5260 return false;
5261 }
5262}
5263
5264// Emit short-circuiting code, where 'right' is never evaluated unless
5265// the left side is true (for &&) or false (for ||).
5266spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5267{
5268 spv::Id boolTypeId = builder.makeBoolType();
5269
5270 // emit left operand
5271 builder.clearAccessChain();
5272 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005273 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005274
5275 // Operands to accumulate OpPhi operands
5276 std::vector<spv::Id> phiOperands;
5277 // accumulate left operand's phi information
5278 phiOperands.push_back(leftId);
5279 phiOperands.push_back(builder.getBuildPoint()->getId());
5280
5281 // Make the two kinds of operation symmetric with a "!"
5282 // || => emit "if (! left) result = right"
5283 // && => emit "if ( left) result = right"
5284 //
5285 // TODO: this runtime "not" for || could be avoided by adding functionality
5286 // to 'builder' to have an "else" without an "then"
5287 if (op == glslang::EOpLogicalOr)
5288 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5289
5290 // make an "if" based on the left value
5291 spv::Builder::If ifBuilder(leftId, builder);
5292
5293 // emit right operand as the "then" part of the "if"
5294 builder.clearAccessChain();
5295 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005296 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005297
5298 // accumulate left operand's phi information
5299 phiOperands.push_back(rightId);
5300 phiOperands.push_back(builder.getBuildPoint()->getId());
5301
5302 // finish the "if"
5303 ifBuilder.makeEndIf();
5304
5305 // phi together the two results
5306 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5307}
5308
Rex Xu9d93a232016-05-05 12:30:44 +08005309// Return type Id of the imported set of extended instructions corresponds to the name.
5310// Import this set if it has not been imported yet.
5311spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5312{
5313 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5314 return extBuiltinMap[name];
5315 else {
Rex Xu51596642016-09-21 18:56:12 +08005316 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005317 spv::Id extBuiltins = builder.import(name);
5318 extBuiltinMap[name] = extBuiltins;
5319 return extBuiltins;
5320 }
5321}
5322
John Kessenich140f3df2015-06-26 16:58:36 -06005323}; // end anonymous namespace
5324
5325namespace glslang {
5326
John Kessenich68d78fd2015-07-12 19:28:10 -06005327void GetSpirvVersion(std::string& version)
5328{
John Kessenich9e55f632015-07-15 10:03:39 -06005329 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005330 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005331 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005332 version = buf;
5333}
5334
John Kessenich140f3df2015-06-26 16:58:36 -06005335// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005336void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005337{
5338 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005339 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005340 if (out.fail())
5341 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005342 for (int i = 0; i < (int)spirv.size(); ++i) {
5343 unsigned int word = spirv[i];
5344 out.write((const char*)&word, 4);
5345 }
5346 out.close();
5347}
5348
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005349// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005350void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005351{
5352 std::ofstream out;
5353 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005354 if (out.fail())
5355 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005356 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005357 if (varName != nullptr) {
5358 out << "\t #pragma once" << std::endl;
5359 out << "const uint32_t " << varName << "[] = {" << std::endl;
5360 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005361 const int WORDS_PER_LINE = 8;
5362 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5363 out << "\t";
5364 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5365 const unsigned int word = spirv[i + j];
5366 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5367 if (i + j + 1 < (int)spirv.size()) {
5368 out << ",";
5369 }
5370 }
5371 out << std::endl;
5372 }
Flavio15017db2017-02-15 14:29:33 -08005373 if (varName != nullptr) {
5374 out << "};";
5375 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005376 out.close();
5377}
5378
John Kessenich140f3df2015-06-26 16:58:36 -06005379//
5380// Set up the glslang traversal
5381//
5382void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5383{
Lei Zhang17535f72016-05-04 15:55:59 -04005384 spv::SpvBuildLogger logger;
5385 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005386}
5387
Lei Zhang17535f72016-05-04 15:55:59 -04005388void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005389{
John Kessenich140f3df2015-06-26 16:58:36 -06005390 TIntermNode* root = intermediate.getTreeRoot();
5391
5392 if (root == 0)
5393 return;
5394
5395 glslang::GetThreadPoolAllocator().push();
5396
Lei Zhang17535f72016-05-04 15:55:59 -04005397 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005398 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005399 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005400 it.dumpSpv(spirv);
5401
5402 glslang::GetThreadPoolAllocator().pop();
5403}
5404
5405}; // end namespace glslang