blob: ceea1e2b171f4ba8ca032445b43dd6895e9a8445 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
46}
John Kessenich140f3df2015-06-26 16:58:36 -060047
48// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020049#include "../glslang/MachineIndependent/localintermediate.h"
50#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060052
John Kessenich140f3df2015-06-26 16:58:36 -060053#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040054#include <list>
55#include <map>
56#include <stack>
57#include <string>
58#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060059
60namespace {
61
John Kessenich55e7d112015-11-15 21:33:39 -070062// For low-order part of the generator's magic number. Bump up
63// when there is a change in the style (e.g., if SSA form changes,
64// or a different instruction sequence to do something gets used).
65const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060066
qining4c912612016-04-01 10:35:16 -040067namespace {
68class SpecConstantOpModeGuard {
69public:
70 SpecConstantOpModeGuard(spv::Builder* builder)
71 : builder_(builder) {
72 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040073 }
74 ~SpecConstantOpModeGuard() {
75 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
76 : builder_->setToNormalCodeGenMode();
77 }
qining40887662016-04-03 22:20:42 -040078 void turnOnSpecConstantOpMode() {
79 builder_->setToSpecConstCodeGenMode();
80 }
qining4c912612016-04-01 10:35:16 -040081
82private:
83 spv::Builder* builder_;
84 bool previous_flag_;
85};
86}
87
John Kessenich140f3df2015-06-26 16:58:36 -060088//
89// The main holder of information for translating glslang to SPIR-V.
90//
91// Derives from the AST walking base class.
92//
93class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
94public:
Lei Zhang17535f72016-05-04 15:55:59 -040095 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060096 virtual ~TGlslangToSpvTraverser();
97
98 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
99 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
100 void visitConstantUnion(glslang::TIntermConstantUnion*);
101 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
102 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
103 void visitSymbol(glslang::TIntermSymbol* symbol);
104 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
105 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
106 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
107
John Kessenich7ba63412015-12-20 17:37:07 -0700108 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110protected:
Rex Xubbceed72016-05-21 09:40:44 +0800111 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700118 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700119 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800120 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700121 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700122 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
123 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
124 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 +0100125 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
128 void makeFunctions(const glslang::TIntermSequence&);
129 void makeGlobalInitializers(const glslang::TIntermSequence&);
130 void visitFunctions(const glslang::TIntermSequence&);
131 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800132 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600133 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
134 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600135 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
136
qining25262b32016-05-06 17:25:16 -0400137 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);
138 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
139 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
140 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800141 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 -0600142 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800143 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich91cef522016-05-05 16:45:40 -0600144 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id 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 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
Lei Zhang17535f72016-05-04 15:55:59 -0400162 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400163
John Kessenich140f3df2015-06-26 16:58:36 -0600164 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
165 spv::Builder builder;
166 bool inMain;
167 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700168 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 -0700169 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600170 const glslang::TIntermediate* glslangIntermediate;
171 spv::Id stdBuiltins;
172
John Kessenich2f273362015-07-18 22:34:27 -0600173 std::unordered_map<int, spv::Id> symbolValues;
174 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
175 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700176 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600177 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 -0600178 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600179};
180
181//
182// Helper functions for translating glslang representations to SPIR-V enumerants.
183//
184
185// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700186spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600187{
John Kessenich66e2faf2016-03-12 18:34:36 -0700188 switch (source) {
189 case glslang::EShSourceGlsl:
190 switch (profile) {
191 case ENoProfile:
192 case ECoreProfile:
193 case ECompatibilityProfile:
194 return spv::SourceLanguageGLSL;
195 case EEsProfile:
196 return spv::SourceLanguageESSL;
197 default:
198 return spv::SourceLanguageUnknown;
199 }
200 case glslang::EShSourceHlsl:
201 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 default:
203 return spv::SourceLanguageUnknown;
204 }
205}
206
207// Translate glslang language (stage) to SPIR-V execution model.
208spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
209{
210 switch (stage) {
211 case EShLangVertex: return spv::ExecutionModelVertex;
212 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
213 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
214 case EShLangGeometry: return spv::ExecutionModelGeometry;
215 case EShLangFragment: return spv::ExecutionModelFragment;
216 case EShLangCompute: return spv::ExecutionModelGLCompute;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::ExecutionModelFragment;
220 }
221}
222
223// Translate glslang type to SPIR-V storage class.
224spv::StorageClass TranslateStorageClass(const glslang::TType& type)
225{
226 if (type.getQualifier().isPipeInput())
227 return spv::StorageClassInput;
228 else if (type.getQualifier().isPipeOutput())
229 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700230 else if (type.getBasicType() == glslang::EbtSampler)
231 return spv::StorageClassUniformConstant;
232 else if (type.getBasicType() == glslang::EbtAtomicUint)
233 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700235 if (type.getQualifier().layoutPushConstant)
236 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 if (type.getBasicType() == glslang::EbtBlock)
238 return spv::StorageClassUniform;
239 else
240 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600241 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600242 } else {
243 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700244 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
245 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
247 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400248 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600250 return spv::StorageClassFunction;
251 }
252 }
253}
254
255// Translate glslang sampler type to SPIR-V dimensionality.
256spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
257{
258 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700259 case glslang::Esd1D: return spv::Dim1D;
260 case glslang::Esd2D: return spv::Dim2D;
261 case glslang::Esd3D: return spv::Dim3D;
262 case glslang::EsdCube: return spv::DimCube;
263 case glslang::EsdRect: return spv::DimRect;
264 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700265 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::Dim2D;
269 }
270}
271
272// Translate glslang type to SPIR-V precision decorations.
273spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
274{
275 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700276 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600277 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 default:
279 return spv::NoPrecision;
280 }
281}
282
283// Translate glslang type to SPIR-V block decorations.
284spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
289 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
298 return (spv::Decoration)spv::BadValue;
299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
327 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
332 return (spv::Decoration)spv::BadValue;
333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600342 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return (spv::Decoration)spv::BadValue;
348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return (spv::Decoration)spv::BadValue;
351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700357// Returns spv::Decoration(spv::BadValue) when no decoration
358// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800359spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
363 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800368 else
369 return (spv::Decoration)spv::BadValue;
370}
371
372// Translate glslang type to SPIR-V auxiliary storage decorations.
373// Returns spv::Decoration(spv::BadValue) when no decoration
374// should be applied.
375spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
376{
377 if (qualifier.patch)
378 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700381 else if (qualifier.sample) {
382 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700384 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600385 return (spv::Decoration)spv::BadValue;
386}
387
John Kessenich92187592016-02-01 13:45:25 -0700388// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700389spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700391 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600392 return spv::DecorationInvariant;
393 else
394 return (spv::Decoration)spv::BadValue;
395}
396
qining9220dbb2016-05-04 17:34:38 -0400397// If glslang type is noContraction, return SPIR-V NoContraction decoration.
398spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
399{
400 if (qualifier.noContraction)
401 return spv::DecorationNoContraction;
402 else
403 return (spv::Decoration)spv::BadValue;
404}
405
David Netoa901ffe2016-06-08 14:11:40 +0100406// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
407// associated capabilities when required. For some built-in variables, a capability
408// is generated only when using the variable in an executable instruction, but not when
409// just declaring a struct member variable with it. This is true for PointSize,
410// ClipDistance, and CullDistance.
411spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600412{
413 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700414 case glslang::EbvPointSize:
David Netoa901ffe2016-06-08 14:11:40 +0100415 // Defer adding the capability until the built-in is actually used.
416 if (!memberDeclaration) {
417 switch (glslangIntermediate->getStage()) {
418 case EShLangGeometry:
419 builder.addCapability(spv::CapabilityGeometryPointSize);
420 break;
421 case EShLangTessControl:
422 case EShLangTessEvaluation:
423 builder.addCapability(spv::CapabilityTessellationPointSize);
424 break;
425 default:
426 break;
427 }
John Kessenich92187592016-02-01 13:45:25 -0700428 }
429 return spv::BuiltInPointSize;
430
John Kessenichebb50532016-05-16 19:22:05 -0600431 // These *Distance capabilities logically belong here, but if the member is declared and
432 // then never used, consumers of SPIR-V prefer the capability not be declared.
433 // They are now generated when used, rather than here when declared.
434 // Potentially, the specification should be more clear what the minimum
435 // use needed is to trigger the capability.
436 //
John Kessenich92187592016-02-01 13:45:25 -0700437 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100438 if (!memberDeclaration)
439 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700440 return spv::BuiltInClipDistance;
441
442 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100443 if (!memberDeclaration)
444 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700445 return spv::BuiltInCullDistance;
446
447 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500448 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700449 return spv::BuiltInViewportIndex;
450
John Kessenich5e801132016-02-15 11:09:46 -0700451 case glslang::EbvSampleId:
452 builder.addCapability(spv::CapabilitySampleRateShading);
453 return spv::BuiltInSampleId;
454
455 case glslang::EbvSamplePosition:
456 builder.addCapability(spv::CapabilitySampleRateShading);
457 return spv::BuiltInSamplePosition;
458
459 case glslang::EbvSampleMask:
460 builder.addCapability(spv::CapabilitySampleRateShading);
461 return spv::BuiltInSampleMask;
462
John Kessenich140f3df2015-06-26 16:58:36 -0600463 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600464 case glslang::EbvVertexId: return spv::BuiltInVertexId;
465 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700466 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
467 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600468 case glslang::EbvBaseVertex:
469 case glslang::EbvBaseInstance:
470 case glslang::EbvDrawId:
471 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600472 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600473 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600474 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
475 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
476 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600477 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
478 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
479 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
480 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
481 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
482 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
483 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600484 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
485 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
486 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
487 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
488 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
489 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
490 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
491 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800492 case glslang::EbvSubGroupSize:
493 case glslang::EbvSubGroupInvocation:
494 case glslang::EbvSubGroupEqMask:
495 case glslang::EbvSubGroupGeMask:
496 case glslang::EbvSubGroupGtMask:
497 case glslang::EbvSubGroupLeMask:
498 case glslang::EbvSubGroupLtMask:
499 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600500 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800501 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 default: return (spv::BuiltIn)spv::BadValue;
503 }
504}
505
Rex Xufc618912015-09-09 16:42:49 +0800506// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700507spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800508{
509 assert(type.getBasicType() == glslang::EbtSampler);
510
John Kessenich5d0fa972016-02-15 11:57:00 -0700511 // Check for capabilities
512 switch (type.getQualifier().layoutFormat) {
513 case glslang::ElfRg32f:
514 case glslang::ElfRg16f:
515 case glslang::ElfR11fG11fB10f:
516 case glslang::ElfR16f:
517 case glslang::ElfRgba16:
518 case glslang::ElfRgb10A2:
519 case glslang::ElfRg16:
520 case glslang::ElfRg8:
521 case glslang::ElfR16:
522 case glslang::ElfR8:
523 case glslang::ElfRgba16Snorm:
524 case glslang::ElfRg16Snorm:
525 case glslang::ElfRg8Snorm:
526 case glslang::ElfR16Snorm:
527 case glslang::ElfR8Snorm:
528
529 case glslang::ElfRg32i:
530 case glslang::ElfRg16i:
531 case glslang::ElfRg8i:
532 case glslang::ElfR16i:
533 case glslang::ElfR8i:
534
535 case glslang::ElfRgb10a2ui:
536 case glslang::ElfRg32ui:
537 case glslang::ElfRg16ui:
538 case glslang::ElfRg8ui:
539 case glslang::ElfR16ui:
540 case glslang::ElfR8ui:
541 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
542 break;
543
544 default:
545 break;
546 }
547
548 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800549 switch (type.getQualifier().layoutFormat) {
550 case glslang::ElfNone: return spv::ImageFormatUnknown;
551 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
552 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
553 case glslang::ElfR32f: return spv::ImageFormatR32f;
554 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
555 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
556 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
557 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
558 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
559 case glslang::ElfR16f: return spv::ImageFormatR16f;
560 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
561 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
562 case glslang::ElfRg16: return spv::ImageFormatRg16;
563 case glslang::ElfRg8: return spv::ImageFormatRg8;
564 case glslang::ElfR16: return spv::ImageFormatR16;
565 case glslang::ElfR8: return spv::ImageFormatR8;
566 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
567 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
568 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
569 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
570 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
571 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
572 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
573 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
574 case glslang::ElfR32i: return spv::ImageFormatR32i;
575 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
576 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
577 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
578 case glslang::ElfR16i: return spv::ImageFormatR16i;
579 case glslang::ElfR8i: return spv::ImageFormatR8i;
580 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
581 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
582 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
583 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
584 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
585 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
586 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
587 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
588 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
589 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
590 default: return (spv::ImageFormat)spv::BadValue;
591 }
592}
593
qining25262b32016-05-06 17:25:16 -0400594// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700595// descriptor set.
596bool IsDescriptorResource(const glslang::TType& type)
597{
John Kessenichf7497e22016-03-08 21:36:22 -0700598 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700599 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700600 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700601
602 // non block...
603 // basically samplerXXX/subpass/sampler/texture are all included
604 // if they are the global-scope-class, not the function parameter
605 // (or local, if they ever exist) class.
606 if (type.getBasicType() == glslang::EbtSampler)
607 return type.getQualifier().isUniformOrBuffer();
608
609 // None of the above.
610 return false;
611}
612
John Kesseniche0b6cad2015-12-24 10:30:13 -0700613void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
614{
615 if (child.layoutMatrix == glslang::ElmNone)
616 child.layoutMatrix = parent.layoutMatrix;
617
618 if (parent.invariant)
619 child.invariant = true;
620 if (parent.nopersp)
621 child.nopersp = true;
622 if (parent.flat)
623 child.flat = true;
624 if (parent.centroid)
625 child.centroid = true;
626 if (parent.patch)
627 child.patch = true;
628 if (parent.sample)
629 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800630 if (parent.coherent)
631 child.coherent = true;
632 if (parent.volatil)
633 child.volatil = true;
634 if (parent.restrict)
635 child.restrict = true;
636 if (parent.readonly)
637 child.readonly = true;
638 if (parent.writeonly)
639 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700640}
641
642bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
643{
John Kessenich7b9fa252016-01-21 18:56:57 -0700644 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700645 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600646 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700647 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600648 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700649}
650
John Kessenich140f3df2015-06-26 16:58:36 -0600651//
652// Implement the TGlslangToSpvTraverser class.
653//
654
Lei Zhang17535f72016-05-04 15:55:59 -0400655TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
656 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
657 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600658 inMain(false), mainTerminated(false), linkageOnly(false),
659 glslangIntermediate(glslangIntermediate)
660{
661 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
662
663 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700664 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600665 stdBuiltins = builder.import("GLSL.std.450");
666 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700667 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
668 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600669
670 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600671 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
672 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600673 builder.addSourceExtension(it->c_str());
674
675 // Add the top-level modes for this shader.
676
John Kessenich92187592016-02-01 13:45:25 -0700677 if (glslangIntermediate->getXfbMode()) {
678 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600679 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700680 }
John Kessenich140f3df2015-06-26 16:58:36 -0600681
682 unsigned int mode;
683 switch (glslangIntermediate->getStage()) {
684 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600685 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600686 break;
687
688 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600689 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600690 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
691 break;
692
693 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600694 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600695 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700696 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
697 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
698 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600699 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703
John Kesseniche6903322015-10-13 16:29:02 -0600704 switch (glslangIntermediate->getVertexSpacing()) {
705 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
706 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
707 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
708 default: mode = spv::BadValue; break;
709 }
710 if (mode != spv::BadValue)
711 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
712
713 switch (glslangIntermediate->getVertexOrder()) {
714 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
715 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
716 default: mode = spv::BadValue; break;
717 }
718 if (mode != spv::BadValue)
719 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
720
721 if (glslangIntermediate->getPointMode())
722 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600723 break;
724
725 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600726 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 switch (glslangIntermediate->getInputPrimitive()) {
728 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
729 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
730 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700731 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600732 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
733 default: mode = spv::BadValue; break;
734 }
735 if (mode != spv::BadValue)
736 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600737
John Kessenich140f3df2015-06-26 16:58:36 -0600738 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
739
740 switch (glslangIntermediate->getOutputPrimitive()) {
741 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
742 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
743 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
744 default: mode = spv::BadValue; break;
745 }
746 if (mode != spv::BadValue)
747 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
748 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
749 break;
750
751 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600752 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600753 if (glslangIntermediate->getPixelCenterInteger())
754 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600755
John Kessenich140f3df2015-06-26 16:58:36 -0600756 if (glslangIntermediate->getOriginUpperLeft())
757 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600758 else
759 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600760
761 if (glslangIntermediate->getEarlyFragmentTests())
762 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
763
764 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600765 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
766 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
767 default: mode = spv::BadValue; break;
768 }
769 if (mode != spv::BadValue)
770 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
771
772 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
773 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600774 break;
775
776 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600777 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600778 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
779 glslangIntermediate->getLocalSize(1),
780 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600781 break;
782
783 default:
784 break;
785 }
786
787}
788
John Kessenich7ba63412015-12-20 17:37:07 -0700789// Finish everything and dump
790void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
791{
792 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100793 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
794 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700795
qiningda397332016-03-09 19:54:03 -0500796 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700797 builder.dump(out);
798}
799
John Kessenich140f3df2015-06-26 16:58:36 -0600800TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
801{
802 if (! mainTerminated) {
803 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
804 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600805 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600806 }
807}
808
809//
810// Implement the traversal functions.
811//
812// Return true from interior nodes to have the external traversal
813// continue on to children. Return false if children were
814// already processed.
815//
816
817//
qining25262b32016-05-06 17:25:16 -0400818// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600819// - uniform/input reads
820// - output writes
821// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
822// - something simple that degenerates into the last bullet
823//
824void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
825{
qining75d1d802016-04-06 14:42:01 -0400826 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
827 if (symbol->getType().getQualifier().isSpecConstant())
828 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
829
John Kessenich140f3df2015-06-26 16:58:36 -0600830 // getSymbolId() will set up all the IO decorations on the first call.
831 // Formal function parameters were mapped during makeFunctions().
832 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700833
834 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
835 if (builder.isPointer(id)) {
836 spv::StorageClass sc = builder.getStorageClass(id);
837 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
838 iOSet.insert(id);
839 }
840
841 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700842 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600843 // Prepare to generate code for the access
844
845 // L-value chains will be computed left to right. We're on the symbol now,
846 // which is the left-most part of the access chain, so now is "clear" time,
847 // followed by setting the base.
848 builder.clearAccessChain();
849
850 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700851 // except for
852 // A) "const in" arguments to a function, which are an intermediate object.
853 // See comments in handleUserFunctionCall().
854 // B) Specialization constants (normal constant don't even come in as a variable),
855 // These are also pure R-values.
856 glslang::TQualifier qualifier = symbol->getQualifier();
857 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
858 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600859 builder.setAccessChainRValue(id);
860 else
861 builder.setAccessChainLValue(id);
862 }
863}
864
865bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
866{
qining40887662016-04-03 22:20:42 -0400867 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
868 if (node->getType().getQualifier().isSpecConstant())
869 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
870
John Kessenich140f3df2015-06-26 16:58:36 -0600871 // First, handle special cases
872 switch (node->getOp()) {
873 case glslang::EOpAssign:
874 case glslang::EOpAddAssign:
875 case glslang::EOpSubAssign:
876 case glslang::EOpMulAssign:
877 case glslang::EOpVectorTimesMatrixAssign:
878 case glslang::EOpVectorTimesScalarAssign:
879 case glslang::EOpMatrixTimesScalarAssign:
880 case glslang::EOpMatrixTimesMatrixAssign:
881 case glslang::EOpDivAssign:
882 case glslang::EOpModAssign:
883 case glslang::EOpAndAssign:
884 case glslang::EOpInclusiveOrAssign:
885 case glslang::EOpExclusiveOrAssign:
886 case glslang::EOpLeftShiftAssign:
887 case glslang::EOpRightShiftAssign:
888 // A bin-op assign "a += b" means the same thing as "a = a + b"
889 // where a is evaluated before b. For a simple assignment, GLSL
890 // says to evaluate the left before the right. So, always, left
891 // node then right node.
892 {
893 // get the left l-value, save it away
894 builder.clearAccessChain();
895 node->getLeft()->traverse(this);
896 spv::Builder::AccessChain lValue = builder.getAccessChain();
897
898 // evaluate the right
899 builder.clearAccessChain();
900 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700901 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600902
903 if (node->getOp() != glslang::EOpAssign) {
904 // the left is also an r-value
905 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700906 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600907
908 // do the operation
qining25262b32016-05-06 17:25:16 -0400909 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
910 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600911 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
912 node->getType().getBasicType());
913
914 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700915 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600916 }
917
918 // store the result
919 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800920 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600921
922 // assignments are expressions having an rValue after they are evaluated...
923 builder.clearAccessChain();
924 builder.setAccessChainRValue(rValue);
925 }
926 return false;
927 case glslang::EOpIndexDirect:
928 case glslang::EOpIndexDirectStruct:
929 {
930 // Get the left part of the access chain.
931 node->getLeft()->traverse(this);
932
933 // Add the next element in the chain
934
David Netoa901ffe2016-06-08 14:11:40 +0100935 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600936 if (! node->getLeft()->getType().isArray() &&
937 node->getLeft()->getType().isVector() &&
938 node->getOp() == glslang::EOpIndexDirect) {
939 // This is essentially a hard-coded vector swizzle of size 1,
940 // so short circuit the access-chain stuff with a swizzle.
941 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100942 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600943 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600944 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100945 int spvIndex = glslangIndex;
946 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
947 node->getOp() == glslang::EOpIndexDirectStruct)
948 {
949 // This may be, e.g., an anonymous block-member selection, which generally need
950 // index remapping due to hidden members in anonymous blocks.
951 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
952 assert(remapper.size() > 0);
953 spvIndex = remapper[glslangIndex];
954 }
John Kessenichebb50532016-05-16 19:22:05 -0600955
David Netoa901ffe2016-06-08 14:11:40 +0100956 // normal case for indexing array or structure or block
957 builder.accessChainPush(builder.makeIntConstant(spvIndex));
958
959 // Add capabilities here for accessing PointSize and clip/cull distance.
960 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600961 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100962 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600963 }
964 }
965 return false;
966 case glslang::EOpIndexIndirect:
967 {
968 // Structure or array or vector indirection.
969 // Will use native SPIR-V access-chain for struct and array indirection;
970 // matrices are arrays of vectors, so will also work for a matrix.
971 // Will use the access chain's 'component' for variable index into a vector.
972
973 // This adapter is building access chains left to right.
974 // Set up the access chain to the left.
975 node->getLeft()->traverse(this);
976
977 // save it so that computing the right side doesn't trash it
978 spv::Builder::AccessChain partial = builder.getAccessChain();
979
980 // compute the next index in the chain
981 builder.clearAccessChain();
982 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700983 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600984
985 // restore the saved access chain
986 builder.setAccessChain(partial);
987
988 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600989 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600990 else
John Kessenichfa668da2015-09-13 14:46:30 -0600991 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600992 }
993 return false;
994 case glslang::EOpVectorSwizzle:
995 {
996 node->getLeft()->traverse(this);
997 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
998 std::vector<unsigned> swizzle;
999 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1000 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -06001001 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001002 }
1003 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001004 case glslang::EOpLogicalOr:
1005 case glslang::EOpLogicalAnd:
1006 {
1007
1008 // These may require short circuiting, but can sometimes be done as straight
1009 // binary operations. The right operand must be short circuited if it has
1010 // side effects, and should probably be if it is complex.
1011 if (isTrivial(node->getRight()->getAsTyped()))
1012 break; // handle below as a normal binary operation
1013 // otherwise, we need to do dynamic short circuiting on the right operand
1014 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1015 builder.clearAccessChain();
1016 builder.setAccessChainRValue(result);
1017 }
1018 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001019 default:
1020 break;
1021 }
1022
1023 // Assume generic binary op...
1024
John Kessenich32cfd492016-02-02 12:37:46 -07001025 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001026 builder.clearAccessChain();
1027 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001028 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001029
John Kessenich32cfd492016-02-02 12:37:46 -07001030 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001031 builder.clearAccessChain();
1032 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001033 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001034
John Kessenich32cfd492016-02-02 12:37:46 -07001035 // get result
1036 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001037 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001038 convertGlslangToSpvType(node->getType()), left, right,
1039 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001040
John Kessenich50e57562015-12-21 21:21:11 -07001041 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001042 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001043 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001044 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001045 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001046 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001047 return false;
1048 }
John Kessenich140f3df2015-06-26 16:58:36 -06001049}
1050
1051bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1052{
qining40887662016-04-03 22:20:42 -04001053 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1054 if (node->getType().getQualifier().isSpecConstant())
1055 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1056
John Kessenichfc51d282015-08-19 13:34:18 -06001057 spv::Id result = spv::NoResult;
1058
1059 // try texturing first
1060 result = createImageTextureFunctionCall(node);
1061 if (result != spv::NoResult) {
1062 builder.clearAccessChain();
1063 builder.setAccessChainRValue(result);
1064
1065 return false; // done with this node
1066 }
1067
1068 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001069
1070 if (node->getOp() == glslang::EOpArrayLength) {
1071 // Quite special; won't want to evaluate the operand.
1072
1073 // Normal .length() would have been constant folded by the front-end.
1074 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001075 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001076 assert(node->getOperand()->getType().isRuntimeSizedArray());
1077 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1078 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001079 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1080 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001081
1082 builder.clearAccessChain();
1083 builder.setAccessChainRValue(length);
1084
1085 return false;
1086 }
1087
John Kessenichfc51d282015-08-19 13:34:18 -06001088 // Start by evaluating the operand
1089
John Kessenich140f3df2015-06-26 16:58:36 -06001090 builder.clearAccessChain();
1091 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001092
Rex Xufc618912015-09-09 16:42:49 +08001093 spv::Id operand = spv::NoResult;
1094
1095 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1096 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001097 node->getOp() == glslang::EOpAtomicCounter ||
1098 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001099 operand = builder.accessChainGetLValue(); // Special case l-value operands
1100 else
John Kessenich32cfd492016-02-02 12:37:46 -07001101 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001102
1103 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001104 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001105
1106 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001107 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001108 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 // if not, then possibly an operation
1111 if (! result)
qining25262b32016-05-06 17:25:16 -04001112 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001113
1114 if (result) {
1115 builder.clearAccessChain();
1116 builder.setAccessChainRValue(result);
1117
1118 return false; // done with this node
1119 }
1120
1121 // it must be a special case, check...
1122 switch (node->getOp()) {
1123 case glslang::EOpPostIncrement:
1124 case glslang::EOpPostDecrement:
1125 case glslang::EOpPreIncrement:
1126 case glslang::EOpPreDecrement:
1127 {
1128 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001129 spv::Id one = 0;
1130 if (node->getBasicType() == glslang::EbtFloat)
1131 one = builder.makeFloatConstant(1.0F);
1132 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1133 one = builder.makeInt64Constant(1);
1134 else
1135 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001136 glslang::TOperator op;
1137 if (node->getOp() == glslang::EOpPreIncrement ||
1138 node->getOp() == glslang::EOpPostIncrement)
1139 op = glslang::EOpAdd;
1140 else
1141 op = glslang::EOpSub;
1142
qining25262b32016-05-06 17:25:16 -04001143 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1144 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001145 convertGlslangToSpvType(node->getType()), operand, one,
1146 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001147 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001148
1149 // The result of operation is always stored, but conditionally the
1150 // consumed result. The consumed result is always an r-value.
1151 builder.accessChainStore(result);
1152 builder.clearAccessChain();
1153 if (node->getOp() == glslang::EOpPreIncrement ||
1154 node->getOp() == glslang::EOpPreDecrement)
1155 builder.setAccessChainRValue(result);
1156 else
1157 builder.setAccessChainRValue(operand);
1158 }
1159
1160 return false;
1161
1162 case glslang::EOpEmitStreamVertex:
1163 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1164 return false;
1165 case glslang::EOpEndStreamPrimitive:
1166 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1167 return false;
1168
1169 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001170 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001171 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001172 }
John Kessenich140f3df2015-06-26 16:58:36 -06001173}
1174
1175bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1176{
qining27e04a02016-04-14 16:40:20 -04001177 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1178 if (node->getType().getQualifier().isSpecConstant())
1179 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1180
John Kessenichfc51d282015-08-19 13:34:18 -06001181 spv::Id result = spv::NoResult;
1182
1183 // try texturing
1184 result = createImageTextureFunctionCall(node);
1185 if (result != spv::NoResult) {
1186 builder.clearAccessChain();
1187 builder.setAccessChainRValue(result);
1188
1189 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001190 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001191 // "imageStore" is a special case, which has no result
1192 return false;
1193 }
John Kessenichfc51d282015-08-19 13:34:18 -06001194
John Kessenich140f3df2015-06-26 16:58:36 -06001195 glslang::TOperator binOp = glslang::EOpNull;
1196 bool reduceComparison = true;
1197 bool isMatrix = false;
1198 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001199 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 assert(node->getOp());
1202
1203 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1204
1205 switch (node->getOp()) {
1206 case glslang::EOpSequence:
1207 {
1208 if (preVisit)
1209 ++sequenceDepth;
1210 else
1211 --sequenceDepth;
1212
1213 if (sequenceDepth == 1) {
1214 // If this is the parent node of all the functions, we want to see them
1215 // early, so all call points have actual SPIR-V functions to reference.
1216 // In all cases, still let the traverser visit the children for us.
1217 makeFunctions(node->getAsAggregate()->getSequence());
1218
1219 // Also, we want all globals initializers to go into the entry of main(), before
1220 // anything else gets there, so visit out of order, doing them all now.
1221 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1222
1223 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1224 // so do them manually.
1225 visitFunctions(node->getAsAggregate()->getSequence());
1226
1227 return false;
1228 }
1229
1230 return true;
1231 }
1232 case glslang::EOpLinkerObjects:
1233 {
1234 if (visit == glslang::EvPreVisit)
1235 linkageOnly = true;
1236 else
1237 linkageOnly = false;
1238
1239 return true;
1240 }
1241 case glslang::EOpComma:
1242 {
1243 // processing from left to right naturally leaves the right-most
1244 // lying around in the access chain
1245 glslang::TIntermSequence& glslangOperands = node->getSequence();
1246 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1247 glslangOperands[i]->traverse(this);
1248
1249 return false;
1250 }
1251 case glslang::EOpFunction:
1252 if (visit == glslang::EvPreVisit) {
1253 if (isShaderEntrypoint(node)) {
1254 inMain = true;
1255 builder.setBuildPoint(shaderEntry->getLastBlock());
1256 } else {
1257 handleFunctionEntry(node);
1258 }
1259 } else {
1260 if (inMain)
1261 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001262 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001263 inMain = false;
1264 }
1265
1266 return true;
1267 case glslang::EOpParameters:
1268 // Parameters will have been consumed by EOpFunction processing, but not
1269 // the body, so we still visited the function node's children, making this
1270 // child redundant.
1271 return false;
1272 case glslang::EOpFunctionCall:
1273 {
1274 if (node->isUserDefined())
1275 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001276 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1277 if (result) {
1278 builder.clearAccessChain();
1279 builder.setAccessChainRValue(result);
1280 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001281 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001282
1283 return false;
1284 }
1285 case glslang::EOpConstructMat2x2:
1286 case glslang::EOpConstructMat2x3:
1287 case glslang::EOpConstructMat2x4:
1288 case glslang::EOpConstructMat3x2:
1289 case glslang::EOpConstructMat3x3:
1290 case glslang::EOpConstructMat3x4:
1291 case glslang::EOpConstructMat4x2:
1292 case glslang::EOpConstructMat4x3:
1293 case glslang::EOpConstructMat4x4:
1294 case glslang::EOpConstructDMat2x2:
1295 case glslang::EOpConstructDMat2x3:
1296 case glslang::EOpConstructDMat2x4:
1297 case glslang::EOpConstructDMat3x2:
1298 case glslang::EOpConstructDMat3x3:
1299 case glslang::EOpConstructDMat3x4:
1300 case glslang::EOpConstructDMat4x2:
1301 case glslang::EOpConstructDMat4x3:
1302 case glslang::EOpConstructDMat4x4:
1303 isMatrix = true;
1304 // fall through
1305 case glslang::EOpConstructFloat:
1306 case glslang::EOpConstructVec2:
1307 case glslang::EOpConstructVec3:
1308 case glslang::EOpConstructVec4:
1309 case glslang::EOpConstructDouble:
1310 case glslang::EOpConstructDVec2:
1311 case glslang::EOpConstructDVec3:
1312 case glslang::EOpConstructDVec4:
1313 case glslang::EOpConstructBool:
1314 case glslang::EOpConstructBVec2:
1315 case glslang::EOpConstructBVec3:
1316 case glslang::EOpConstructBVec4:
1317 case glslang::EOpConstructInt:
1318 case glslang::EOpConstructIVec2:
1319 case glslang::EOpConstructIVec3:
1320 case glslang::EOpConstructIVec4:
1321 case glslang::EOpConstructUint:
1322 case glslang::EOpConstructUVec2:
1323 case glslang::EOpConstructUVec3:
1324 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001325 case glslang::EOpConstructInt64:
1326 case glslang::EOpConstructI64Vec2:
1327 case glslang::EOpConstructI64Vec3:
1328 case glslang::EOpConstructI64Vec4:
1329 case glslang::EOpConstructUint64:
1330 case glslang::EOpConstructU64Vec2:
1331 case glslang::EOpConstructU64Vec3:
1332 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001333 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001334 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001335 {
1336 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001337 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001338 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1339 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001340 if (node->getOp() == glslang::EOpConstructTextureSampler)
1341 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1342 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001343 std::vector<spv::Id> constituents;
1344 for (int c = 0; c < (int)arguments.size(); ++c)
1345 constituents.push_back(arguments[c]);
1346 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001347 } else if (isMatrix)
1348 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1349 else
1350 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 builder.clearAccessChain();
1353 builder.setAccessChainRValue(constructed);
1354
1355 return false;
1356 }
1357
1358 // These six are component-wise compares with component-wise results.
1359 // Forward on to createBinaryOperation(), requesting a vector result.
1360 case glslang::EOpLessThan:
1361 case glslang::EOpGreaterThan:
1362 case glslang::EOpLessThanEqual:
1363 case glslang::EOpGreaterThanEqual:
1364 case glslang::EOpVectorEqual:
1365 case glslang::EOpVectorNotEqual:
1366 {
1367 // Map the operation to a binary
1368 binOp = node->getOp();
1369 reduceComparison = false;
1370 switch (node->getOp()) {
1371 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1372 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1373 default: binOp = node->getOp(); break;
1374 }
1375
1376 break;
1377 }
1378 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001379 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001380 binOp = glslang::EOpMul;
1381 break;
1382 case glslang::EOpOuterProduct:
1383 // two vectors multiplied to make a matrix
1384 binOp = glslang::EOpOuterProduct;
1385 break;
1386 case glslang::EOpDot:
1387 {
qining25262b32016-05-06 17:25:16 -04001388 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001389 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001390 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001391 binOp = glslang::EOpMul;
1392 break;
1393 }
1394 case glslang::EOpMod:
1395 // when an aggregate, this is the floating-point mod built-in function,
1396 // which can be emitted by the one in createBinaryOperation()
1397 binOp = glslang::EOpMod;
1398 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001399 case glslang::EOpEmitVertex:
1400 case glslang::EOpEndPrimitive:
1401 case glslang::EOpBarrier:
1402 case glslang::EOpMemoryBarrier:
1403 case glslang::EOpMemoryBarrierAtomicCounter:
1404 case glslang::EOpMemoryBarrierBuffer:
1405 case glslang::EOpMemoryBarrierImage:
1406 case glslang::EOpMemoryBarrierShared:
1407 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001408 case glslang::EOpAllMemoryBarrierWithGroupSync:
1409 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1410 case glslang::EOpWorkgroupMemoryBarrier:
1411 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001412 noReturnValue = true;
1413 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1414 break;
1415
John Kessenich426394d2015-07-23 10:22:48 -06001416 case glslang::EOpAtomicAdd:
1417 case glslang::EOpAtomicMin:
1418 case glslang::EOpAtomicMax:
1419 case glslang::EOpAtomicAnd:
1420 case glslang::EOpAtomicOr:
1421 case glslang::EOpAtomicXor:
1422 case glslang::EOpAtomicExchange:
1423 case glslang::EOpAtomicCompSwap:
1424 atomic = true;
1425 break;
1426
John Kessenich140f3df2015-06-26 16:58:36 -06001427 default:
1428 break;
1429 }
1430
1431 //
1432 // See if it maps to a regular operation.
1433 //
John Kessenich140f3df2015-06-26 16:58:36 -06001434 if (binOp != glslang::EOpNull) {
1435 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1436 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1437 assert(left && right);
1438
1439 builder.clearAccessChain();
1440 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001441 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001442
1443 builder.clearAccessChain();
1444 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001445 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001446
qining25262b32016-05-06 17:25:16 -04001447 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1448 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001449 left->getType().getBasicType(), reduceComparison);
1450
1451 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001452 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001453 builder.clearAccessChain();
1454 builder.setAccessChainRValue(result);
1455
1456 return false;
1457 }
1458
John Kessenich426394d2015-07-23 10:22:48 -06001459 //
1460 // Create the list of operands.
1461 //
John Kessenich140f3df2015-06-26 16:58:36 -06001462 glslang::TIntermSequence& glslangOperands = node->getSequence();
1463 std::vector<spv::Id> operands;
1464 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1465 builder.clearAccessChain();
1466 glslangOperands[arg]->traverse(this);
1467
1468 // special case l-value operands; there are just a few
1469 bool lvalue = false;
1470 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001471 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001472 case glslang::EOpModf:
1473 if (arg == 1)
1474 lvalue = true;
1475 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001476 case glslang::EOpInterpolateAtSample:
1477 case glslang::EOpInterpolateAtOffset:
1478 if (arg == 0)
1479 lvalue = true;
1480 break;
Rex Xud4782c12015-09-06 16:30:11 +08001481 case glslang::EOpAtomicAdd:
1482 case glslang::EOpAtomicMin:
1483 case glslang::EOpAtomicMax:
1484 case glslang::EOpAtomicAnd:
1485 case glslang::EOpAtomicOr:
1486 case glslang::EOpAtomicXor:
1487 case glslang::EOpAtomicExchange:
1488 case glslang::EOpAtomicCompSwap:
1489 if (arg == 0)
1490 lvalue = true;
1491 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001492 case glslang::EOpAddCarry:
1493 case glslang::EOpSubBorrow:
1494 if (arg == 2)
1495 lvalue = true;
1496 break;
1497 case glslang::EOpUMulExtended:
1498 case glslang::EOpIMulExtended:
1499 if (arg >= 2)
1500 lvalue = true;
1501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001502 default:
1503 break;
1504 }
1505 if (lvalue)
1506 operands.push_back(builder.accessChainGetLValue());
1507 else
John Kessenich32cfd492016-02-02 12:37:46 -07001508 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001509 }
John Kessenich426394d2015-07-23 10:22:48 -06001510
1511 if (atomic) {
1512 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001513 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001514 } else {
1515 // Pass through to generic operations.
1516 switch (glslangOperands.size()) {
1517 case 0:
1518 result = createNoArgOperation(node->getOp());
1519 break;
1520 case 1:
qining25262b32016-05-06 17:25:16 -04001521 result = createUnaryOperation(
1522 node->getOp(), precision,
1523 TranslateNoContractionDecoration(node->getType().getQualifier()),
1524 convertGlslangToSpvType(node->getType()), operands.front(),
1525 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001526 break;
1527 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001528 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001529 break;
1530 }
John Kessenich140f3df2015-06-26 16:58:36 -06001531 }
1532
1533 if (noReturnValue)
1534 return false;
1535
1536 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001537 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001538 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001539 } else {
1540 builder.clearAccessChain();
1541 builder.setAccessChainRValue(result);
1542 return false;
1543 }
1544}
1545
1546bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1547{
1548 // This path handles both if-then-else and ?:
1549 // The if-then-else has a node type of void, while
1550 // ?: has a non-void node type
1551 spv::Id result = 0;
1552 if (node->getBasicType() != glslang::EbtVoid) {
1553 // don't handle this as just on-the-fly temporaries, because there will be two names
1554 // and better to leave SSA to later passes
1555 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1556 }
1557
1558 // emit the condition before doing anything with selection
1559 node->getCondition()->traverse(this);
1560
1561 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001562 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001563
1564 if (node->getTrueBlock()) {
1565 // emit the "then" statement
1566 node->getTrueBlock()->traverse(this);
1567 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001568 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001569 }
1570
1571 if (node->getFalseBlock()) {
1572 ifBuilder.makeBeginElse();
1573 // emit the "else" statement
1574 node->getFalseBlock()->traverse(this);
1575 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001576 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001577 }
1578
1579 ifBuilder.makeEndIf();
1580
1581 if (result) {
1582 // GLSL only has r-values as the result of a :?, but
1583 // if we have an l-value, that can be more efficient if it will
1584 // become the base of a complex r-value expression, because the
1585 // next layer copies r-values into memory to use the access-chain mechanism
1586 builder.clearAccessChain();
1587 builder.setAccessChainLValue(result);
1588 }
1589
1590 return false;
1591}
1592
1593bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1594{
1595 // emit and get the condition before doing anything with switch
1596 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001597 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001598
1599 // browse the children to sort out code segments
1600 int defaultSegment = -1;
1601 std::vector<TIntermNode*> codeSegments;
1602 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1603 std::vector<int> caseValues;
1604 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1605 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1606 TIntermNode* child = *c;
1607 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001608 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001609 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001610 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001611 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1612 } else
1613 codeSegments.push_back(child);
1614 }
1615
qining25262b32016-05-06 17:25:16 -04001616 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001617 // statements between the last case and the end of the switch statement
1618 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1619 (int)codeSegments.size() == defaultSegment)
1620 codeSegments.push_back(nullptr);
1621
1622 // make the switch statement
1623 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001624 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001625
1626 // emit all the code in the segments
1627 breakForLoop.push(false);
1628 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1629 builder.nextSwitchSegment(segmentBlocks, s);
1630 if (codeSegments[s])
1631 codeSegments[s]->traverse(this);
1632 else
1633 builder.addSwitchBreak();
1634 }
1635 breakForLoop.pop();
1636
1637 builder.endSwitch(segmentBlocks);
1638
1639 return false;
1640}
1641
1642void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1643{
1644 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001645 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001646
1647 builder.clearAccessChain();
1648 builder.setAccessChainRValue(constant);
1649}
1650
1651bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1652{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001653 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001654 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001655 // Spec requires back edges to target header blocks, and every header block
1656 // must dominate its merge block. Make a header block first to ensure these
1657 // conditions are met. By definition, it will contain OpLoopMerge, followed
1658 // by a block-ending branch. But we don't want to put any other body/test
1659 // instructions in it, since the body/test may have arbitrary instructions,
1660 // including merges of its own.
1661 builder.setBuildPoint(&blocks.head);
1662 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001663 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001664 spv::Block& test = builder.makeNewBlock();
1665 builder.createBranch(&test);
1666
1667 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001668 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001669 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001670 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1672
1673 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001674 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001675 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001676 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001677 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001678 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001679
1680 builder.setBuildPoint(&blocks.continue_target);
1681 if (node->getTerminal())
1682 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001683 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001684 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001685 builder.createBranch(&blocks.body);
1686
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001687 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001688 builder.setBuildPoint(&blocks.body);
1689 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001690 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001691 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001692 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001693
1694 builder.setBuildPoint(&blocks.continue_target);
1695 if (node->getTerminal())
1696 node->getTerminal()->traverse(this);
1697 if (node->getTest()) {
1698 node->getTest()->traverse(this);
1699 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001700 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001701 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001702 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001703 // TODO: unless there was a break/return/discard instruction
1704 // somewhere in the body, this is an infinite loop, so we should
1705 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001706 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001707 }
John Kessenich140f3df2015-06-26 16:58:36 -06001708 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001709 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001710 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001711 return false;
1712}
1713
1714bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1715{
1716 if (node->getExpression())
1717 node->getExpression()->traverse(this);
1718
1719 switch (node->getFlowOp()) {
1720 case glslang::EOpKill:
1721 builder.makeDiscard();
1722 break;
1723 case glslang::EOpBreak:
1724 if (breakForLoop.top())
1725 builder.createLoopExit();
1726 else
1727 builder.addSwitchBreak();
1728 break;
1729 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001730 builder.createLoopContinue();
1731 break;
1732 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001733 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001734 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001735 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001736 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001737
1738 builder.clearAccessChain();
1739 break;
1740
1741 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001742 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001743 break;
1744 }
1745
1746 return false;
1747}
1748
1749spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1750{
qining25262b32016-05-06 17:25:16 -04001751 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001752 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001753 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001754 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001755 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001756 }
1757
1758 // Now, handle actual variables
1759 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1760 spv::Id spvType = convertGlslangToSpvType(node->getType());
1761
1762 const char* name = node->getName().c_str();
1763 if (glslang::IsAnonymous(name))
1764 name = "";
1765
1766 return builder.createVariable(storageClass, spvType, name);
1767}
1768
1769// Return type Id of the sampled type.
1770spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1771{
1772 switch (sampler.type) {
1773 case glslang::EbtFloat: return builder.makeFloatType(32);
1774 case glslang::EbtInt: return builder.makeIntType(32);
1775 case glslang::EbtUint: return builder.makeUintType(32);
1776 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001777 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001778 return builder.makeFloatType(32);
1779 }
1780}
1781
John Kessenich3ac051e2015-12-20 11:29:16 -07001782// Convert from a glslang type to an SPV type, by calling into a
1783// recursive version of this function. This establishes the inherited
1784// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001785spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1786{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001788}
1789
1790// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001791// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001792spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001793{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001794 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001795
1796 switch (type.getBasicType()) {
1797 case glslang::EbtVoid:
1798 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001799 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001800 break;
1801 case glslang::EbtFloat:
1802 spvType = builder.makeFloatType(32);
1803 break;
1804 case glslang::EbtDouble:
1805 spvType = builder.makeFloatType(64);
1806 break;
1807 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001808 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1809 // a 32-bit int where non-0 means true.
1810 if (explicitLayout != glslang::ElpNone)
1811 spvType = builder.makeUintType(32);
1812 else
1813 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001814 break;
1815 case glslang::EbtInt:
1816 spvType = builder.makeIntType(32);
1817 break;
1818 case glslang::EbtUint:
1819 spvType = builder.makeUintType(32);
1820 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001821 case glslang::EbtInt64:
1822 builder.addCapability(spv::CapabilityInt64);
1823 spvType = builder.makeIntType(64);
1824 break;
1825 case glslang::EbtUint64:
1826 builder.addCapability(spv::CapabilityInt64);
1827 spvType = builder.makeUintType(64);
1828 break;
John Kessenich426394d2015-07-23 10:22:48 -06001829 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001830 logger->tbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
John Kessenich426394d2015-07-23 10:22:48 -06001831 spvType = builder.makeUintType(32);
1832 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001833 case glslang::EbtSampler:
1834 {
1835 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001836 if (sampler.sampler) {
1837 // pure sampler
1838 spvType = builder.makeSamplerType();
1839 } else {
1840 // an image is present, make its type
1841 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1842 sampler.image ? 2 : 1, TranslateImageFormat(type));
1843 if (sampler.combined) {
1844 // already has both image and sampler, make the combined type
1845 spvType = builder.makeSampledImageType(spvType);
1846 }
John Kessenich55e7d112015-11-15 21:33:39 -07001847 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001848 }
John Kessenich140f3df2015-06-26 16:58:36 -06001849 break;
1850 case glslang::EbtStruct:
1851 case glslang::EbtBlock:
1852 {
1853 // If we've seen this struct type, return it
1854 const glslang::TTypeList* glslangStruct = type.getStruct();
1855 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001856
1857 // Try to share structs for different layouts, but not yet for other
1858 // kinds of qualification (primarily not yet including interpolant qualification).
1859 if (! HasNonLayoutQualifiers(qualifier))
1860 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1861 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001862 break;
1863
1864 // else, we haven't seen it...
1865
1866 // Create a vector of struct types for SPIR-V to consume
1867 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1868 if (type.getBasicType() == glslang::EbtBlock)
1869 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001870 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001871 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1872 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1873 if (glslangType.hiddenMember()) {
1874 ++memberDelta;
1875 if (type.getBasicType() == glslang::EbtBlock)
1876 memberRemapper[glslangStruct][i] = -1;
1877 } else {
1878 if (type.getBasicType() == glslang::EbtBlock)
1879 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001880 // modify just this child's view of the qualifier
1881 glslang::TQualifier subQualifier = glslangType.getQualifier();
1882 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001883
1884 // manually inherit location; it's more complex
1885 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1886 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1887 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001888 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001889
1890 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001892 }
1893 }
1894
1895 // Make the SPIR-V type
1896 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001897 if (! HasNonLayoutQualifiers(qualifier))
1898 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001899
1900 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001901 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001902 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001903 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1904 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1905 int member = i;
1906 if (type.getBasicType() == glslang::EbtBlock)
1907 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001908
John Kesseniche0b6cad2015-12-24 10:30:13 -07001909 // modify just this child's view of the qualifier
1910 glslang::TQualifier subQualifier = glslangType.getQualifier();
1911 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001912
John Kessenich140f3df2015-06-26 16:58:36 -06001913 // using -1 above to indicate a hidden member
1914 if (member >= 0) {
1915 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001916 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001917 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001918 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001919 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06001920 if (type.getBasicType() == glslang::EbtBlock) {
1921 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1922 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
1923 }
scygan8add1512016-05-06 16:54:54 +02001924 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001925 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001926
Rex Xu1da878f2016-02-21 20:59:01 +08001927 if (qualifier.storage == glslang::EvqBuffer) {
1928 std::vector<spv::Decoration> memory;
1929 TranslateMemoryDecoration(subQualifier, memory);
1930 for (unsigned int i = 0; i < memory.size(); ++i)
1931 addMemberDecoration(spvType, member, memory[i]);
1932 }
1933
John Kessenich09677482016-02-19 12:21:50 -07001934 // compute location decoration; tricky based on whether inheritance is at play
1935 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1936 // probably move to the linker stage of the front end proper, and just have the
1937 // answer sitting already distributed throughout the individual member locations.
1938 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001939 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001940 // struct members should not have explicit locations
1941 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001942 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001943 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001944 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1945 // The members, and their nested types, must not themselves have Location decorations.
1946 }
John Kessenich09677482016-02-19 12:21:50 -07001947 else if (qualifier.hasLocation()) // inheritance
1948 location = qualifier.layoutLocation + locationOffset;
1949 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001950 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001951 if (location >= 0)
1952 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1953
1954 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001955 if (glslangType.getQualifier().hasComponent())
1956 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1957 if (glslangType.getQualifier().hasXfbOffset())
1958 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001959 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001960 // figure out what to do with offset, which is accumulating
1961 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001962 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001963 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001964 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001965 offset = nextOffset;
1966 }
John Kessenich140f3df2015-06-26 16:58:36 -06001967
John Kessenichf85e8062015-12-19 13:57:10 -07001968 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001969 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001970
John Kessenich140f3df2015-06-26 16:58:36 -06001971 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001972 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001973 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001974 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001975 }
1976 }
1977
1978 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001979 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001980 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001981 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001982 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001983 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001984 }
John Kessenich140f3df2015-06-26 16:58:36 -06001985 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001986 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001987 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001988 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001989 if (type.getQualifier().hasXfbBuffer())
1990 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1991 }
1992 }
1993 break;
1994 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001995 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001996 break;
1997 }
1998
1999 if (type.isMatrix())
2000 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2001 else {
2002 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2003 if (type.getVectorSize() > 1)
2004 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2005 }
2006
2007 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002008 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2009
John Kessenichc9a80832015-09-12 12:17:44 -06002010 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002011 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002012 // We need to decorate array strides for types needing explicit layout, except blocks.
2013 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002014 // Use a dummy glslang type for querying internal strides of
2015 // arrays of arrays, but using just a one-dimensional array.
2016 glslang::TType simpleArrayType(type, 0); // deference type of the array
2017 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2018 simpleArrayType.getArraySizes().dereference();
2019
2020 // Will compute the higher-order strides here, rather than making a whole
2021 // pile of types and doing repetitive recursion on their contents.
2022 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2023 }
John Kessenichf8842e52016-01-04 19:22:56 -07002024
2025 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002026 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002027 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002028 if (stride > 0)
2029 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002030 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002031 }
2032 } else {
2033 // single-dimensional array, and don't yet have stride
2034
John Kessenichf8842e52016-01-04 19:22:56 -07002035 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002036 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2037 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002038 }
John Kessenich31ed4832015-09-09 17:51:38 -06002039
John Kessenichc9a80832015-09-12 12:17:44 -06002040 // Do the outer dimension, which might not be known for a runtime-sized array
2041 if (type.isRuntimeSizedArray()) {
2042 spvType = builder.makeRuntimeArray(spvType);
2043 } else {
2044 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002045 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002046 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002047 if (stride > 0)
2048 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002049 }
2050
2051 return spvType;
2052}
2053
John Kessenich6c292d32016-02-15 20:58:50 -07002054// Turn the expression forming the array size into an id.
2055// This is not quite trivial, because of specialization constants.
2056// Sometimes, a raw constant is turned into an Id, and sometimes
2057// a specialization constant expression is.
2058spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2059{
2060 // First, see if this is sized with a node, meaning a specialization constant:
2061 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2062 if (specNode != nullptr) {
2063 builder.clearAccessChain();
2064 specNode->traverse(this);
2065 return accessChainLoad(specNode->getAsTyped()->getType());
2066 }
qining25262b32016-05-06 17:25:16 -04002067
John Kessenich6c292d32016-02-15 20:58:50 -07002068 // Otherwise, need a compile-time (front end) size, get it:
2069 int size = arraySizes.getDimSize(dim);
2070 assert(size > 0);
2071 return builder.makeUintConstant(size);
2072}
2073
John Kessenich103bef92016-02-08 21:38:15 -07002074// Wrap the builder's accessChainLoad to:
2075// - localize handling of RelaxedPrecision
2076// - use the SPIR-V inferred type instead of another conversion of the glslang type
2077// (avoids unnecessary work and possible type punning for structures)
2078// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002079spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2080{
John Kessenich103bef92016-02-08 21:38:15 -07002081 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2082 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2083
2084 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002085 if (type.getBasicType() == glslang::EbtBool) {
2086 if (builder.isScalarType(nominalTypeId)) {
2087 // Conversion for bool
2088 spv::Id boolType = builder.makeBoolType();
2089 if (nominalTypeId != boolType)
2090 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2091 } else if (builder.isVectorType(nominalTypeId)) {
2092 // Conversion for bvec
2093 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2094 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2095 if (nominalTypeId != bvecType)
2096 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2097 }
2098 }
John Kessenich103bef92016-02-08 21:38:15 -07002099
2100 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002101}
2102
Rex Xu27253232016-02-23 17:51:09 +08002103// Wrap the builder's accessChainStore to:
2104// - do conversion of concrete to abstract type
2105void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2106{
2107 // Need to convert to abstract types when necessary
2108 if (type.getBasicType() == glslang::EbtBool) {
2109 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2110
2111 if (builder.isScalarType(nominalTypeId)) {
2112 // Conversion for bool
2113 spv::Id boolType = builder.makeBoolType();
2114 if (nominalTypeId != boolType) {
2115 spv::Id zero = builder.makeUintConstant(0);
2116 spv::Id one = builder.makeUintConstant(1);
2117 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2118 }
2119 } else if (builder.isVectorType(nominalTypeId)) {
2120 // Conversion for bvec
2121 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2122 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2123 if (nominalTypeId != bvecType) {
2124 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2125 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2126 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2127 }
2128 }
2129 }
2130
2131 builder.accessChainStore(rvalue);
2132}
2133
John Kessenichf85e8062015-12-19 13:57:10 -07002134// Decide whether or not this type should be
2135// decorated with offsets and strides, and if so
2136// whether std140 or std430 rules should be applied.
2137glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002138{
John Kessenichf85e8062015-12-19 13:57:10 -07002139 // has to be a block
2140 if (type.getBasicType() != glslang::EbtBlock)
2141 return glslang::ElpNone;
2142
2143 // has to be a uniform or buffer block
2144 if (type.getQualifier().storage != glslang::EvqUniform &&
2145 type.getQualifier().storage != glslang::EvqBuffer)
2146 return glslang::ElpNone;
2147
2148 // return the layout to use
2149 switch (type.getQualifier().layoutPacking) {
2150 case glslang::ElpStd140:
2151 case glslang::ElpStd430:
2152 return type.getQualifier().layoutPacking;
2153 default:
2154 return glslang::ElpNone;
2155 }
John Kessenich31ed4832015-09-09 17:51:38 -06002156}
2157
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002158// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002159int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002160{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002161 int size;
John Kessenich49987892015-12-29 17:11:44 -07002162 int stride;
2163 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002164
2165 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002166}
2167
John Kessenich49987892015-12-29 17:11:44 -07002168// 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 -07002169// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002170int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002171{
John Kessenich49987892015-12-29 17:11:44 -07002172 glslang::TType elementType;
2173 elementType.shallowCopy(matrixType);
2174 elementType.clearArraySizes();
2175
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002176 int size;
John Kessenich49987892015-12-29 17:11:44 -07002177 int stride;
2178 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2179
2180 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002181}
2182
John Kessenich5e4b1242015-08-06 22:53:06 -06002183// Given a member type of a struct, realign the current offset for it, and compute
2184// the next (not yet aligned) offset for the next member, which will get aligned
2185// on the next call.
2186// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2187// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2188// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002189void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002190 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002191{
2192 // this will get a positive value when deemed necessary
2193 nextOffset = -1;
2194
John Kessenich5e4b1242015-08-06 22:53:06 -06002195 // override anything in currentOffset with user-set offset
2196 if (memberType.getQualifier().hasOffset())
2197 currentOffset = memberType.getQualifier().layoutOffset;
2198
2199 // It could be that current linker usage in glslang updated all the layoutOffset,
2200 // in which case the following code does not matter. But, that's not quite right
2201 // once cross-compilation unit GLSL validation is done, as the original user
2202 // settings are needed in layoutOffset, and then the following will come into play.
2203
John Kessenichf85e8062015-12-19 13:57:10 -07002204 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002205 if (! memberType.getQualifier().hasOffset())
2206 currentOffset = -1;
2207
2208 return;
2209 }
2210
John Kessenichf85e8062015-12-19 13:57:10 -07002211 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002212 if (currentOffset < 0)
2213 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002214
John Kessenich5e4b1242015-08-06 22:53:06 -06002215 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2216 // but possibly not yet correctly aligned.
2217
2218 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002219 int dummyStride;
2220 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002221 glslang::RoundToPow2(currentOffset, memberAlignment);
2222 nextOffset = currentOffset + memberSize;
2223}
2224
David Netoa901ffe2016-06-08 14:11:40 +01002225void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002226{
David Netoa901ffe2016-06-08 14:11:40 +01002227 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2228 switch (glslangBuiltIn)
2229 {
2230 case glslang::EbvClipDistance:
2231 case glslang::EbvCullDistance:
2232 case glslang::EbvPointSize:
2233 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2234 // Alternately, we could just call this for any glslang built-in, since the
2235 // capability already guards against duplicates.
2236 TranslateBuiltInDecoration(glslangBuiltIn, false);
2237 break;
2238 default:
2239 // Capabilities were already generated when the struct was declared.
2240 break;
2241 }
John Kessenichebb50532016-05-16 19:22:05 -06002242}
2243
John Kessenich140f3df2015-06-26 16:58:36 -06002244bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2245{
John Kessenich4d65ee32016-03-12 18:17:47 -07002246 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002247 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002248 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002249}
2250
2251// Make all the functions, skeletally, without actually visiting their bodies.
2252void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2253{
2254 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2255 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2256 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2257 continue;
2258
2259 // We're on a user function. Set up the basic interface for the function now,
2260 // so that it's available to call.
2261 // Translating the body will happen later.
2262 //
qining25262b32016-05-06 17:25:16 -04002263 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002264 // function. What it is an address of varies:
2265 //
2266 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2267 // so that write needs to be to a copy, hence the address of a copy works.
2268 //
2269 // - "const in" parameters can just be the r-value, as no writes need occur.
2270 //
2271 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2272 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2273
2274 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002275 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002276 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2277
2278 for (int p = 0; p < (int)parameters.size(); ++p) {
2279 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2280 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002281 if (paramType.isOpaque())
2282 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2283 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002284 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2285 else
2286 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002287 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002288 paramTypes.push_back(typeId);
2289 }
2290
2291 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002292 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2293 convertGlslangToSpvType(glslFunction->getType()),
2294 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002295
2296 // Track function to emit/call later
2297 functionMap[glslFunction->getName().c_str()] = function;
2298
2299 // Set the parameter id's
2300 for (int p = 0; p < (int)parameters.size(); ++p) {
2301 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2302 // give a name too
2303 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2304 }
2305 }
2306}
2307
2308// Process all the initializers, while skipping the functions and link objects
2309void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2310{
2311 builder.setBuildPoint(shaderEntry->getLastBlock());
2312 for (int i = 0; i < (int)initializers.size(); ++i) {
2313 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2314 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2315
2316 // We're on a top-level node that's not a function. Treat as an initializer, whose
2317 // code goes into the beginning of main.
2318 initializer->traverse(this);
2319 }
2320 }
2321}
2322
2323// Process all the functions, while skipping initializers.
2324void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2325{
2326 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2327 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2328 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2329 node->traverse(this);
2330 }
2331}
2332
2333void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2334{
qining25262b32016-05-06 17:25:16 -04002335 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002336 // that called makeFunctions().
2337 spv::Function* function = functionMap[node->getName().c_str()];
2338 spv::Block* functionBlock = function->getEntryBlock();
2339 builder.setBuildPoint(functionBlock);
2340}
2341
Rex Xu04db3f52015-09-16 11:44:02 +08002342void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002343{
Rex Xufc618912015-09-09 16:42:49 +08002344 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002345
2346 glslang::TSampler sampler = {};
2347 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002348 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002349 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2350 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2351 }
2352
John Kessenich140f3df2015-06-26 16:58:36 -06002353 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2354 builder.clearAccessChain();
2355 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002356
2357 // Special case l-value operands
2358 bool lvalue = false;
2359 switch (node.getOp()) {
2360 case glslang::EOpImageAtomicAdd:
2361 case glslang::EOpImageAtomicMin:
2362 case glslang::EOpImageAtomicMax:
2363 case glslang::EOpImageAtomicAnd:
2364 case glslang::EOpImageAtomicOr:
2365 case glslang::EOpImageAtomicXor:
2366 case glslang::EOpImageAtomicExchange:
2367 case glslang::EOpImageAtomicCompSwap:
2368 if (i == 0)
2369 lvalue = true;
2370 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002371 case glslang::EOpSparseImageLoad:
2372 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2373 lvalue = true;
2374 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002375 case glslang::EOpSparseTexture:
2376 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2377 lvalue = true;
2378 break;
2379 case glslang::EOpSparseTextureClamp:
2380 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2381 lvalue = true;
2382 break;
2383 case glslang::EOpSparseTextureLod:
2384 case glslang::EOpSparseTextureOffset:
2385 if (i == 3)
2386 lvalue = true;
2387 break;
2388 case glslang::EOpSparseTextureFetch:
2389 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2390 lvalue = true;
2391 break;
2392 case glslang::EOpSparseTextureFetchOffset:
2393 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2394 lvalue = true;
2395 break;
2396 case glslang::EOpSparseTextureLodOffset:
2397 case glslang::EOpSparseTextureGrad:
2398 case glslang::EOpSparseTextureOffsetClamp:
2399 if (i == 4)
2400 lvalue = true;
2401 break;
2402 case glslang::EOpSparseTextureGradOffset:
2403 case glslang::EOpSparseTextureGradClamp:
2404 if (i == 5)
2405 lvalue = true;
2406 break;
2407 case glslang::EOpSparseTextureGradOffsetClamp:
2408 if (i == 6)
2409 lvalue = true;
2410 break;
2411 case glslang::EOpSparseTextureGather:
2412 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2413 lvalue = true;
2414 break;
2415 case glslang::EOpSparseTextureGatherOffset:
2416 case glslang::EOpSparseTextureGatherOffsets:
2417 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2418 lvalue = true;
2419 break;
Rex Xufc618912015-09-09 16:42:49 +08002420 default:
2421 break;
2422 }
2423
Rex Xu6b86d492015-09-16 17:48:22 +08002424 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002425 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002426 else
John Kessenich32cfd492016-02-02 12:37:46 -07002427 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002428 }
2429}
2430
John Kessenichfc51d282015-08-19 13:34:18 -06002431void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002432{
John Kessenichfc51d282015-08-19 13:34:18 -06002433 builder.clearAccessChain();
2434 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002435 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002436}
John Kessenich140f3df2015-06-26 16:58:36 -06002437
John Kessenichfc51d282015-08-19 13:34:18 -06002438spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2439{
Rex Xufc618912015-09-09 16:42:49 +08002440 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002441 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002442 }
2443
John Kessenichfc51d282015-08-19 13:34:18 -06002444 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002445 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2446 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2447 std::vector<spv::Id> arguments;
2448 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002449 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002450 else
2451 translateArguments(*node->getAsUnaryNode(), arguments);
2452 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2453
2454 spv::Builder::TextureParameters params = { };
2455 params.sampler = arguments[0];
2456
Rex Xu04db3f52015-09-16 11:44:02 +08002457 glslang::TCrackedTextureOp cracked;
2458 node->crackTexture(sampler, cracked);
2459
John Kessenichfc51d282015-08-19 13:34:18 -06002460 // Check for queries
2461 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002462 // a sampled image needs to have the image extracted first
2463 if (builder.isSampledImage(params.sampler))
2464 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002465 switch (node->getOp()) {
2466 case glslang::EOpImageQuerySize:
2467 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002468 if (arguments.size() > 1) {
2469 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002470 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002471 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002472 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002473 case glslang::EOpImageQuerySamples:
2474 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002475 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002476 case glslang::EOpTextureQueryLod:
2477 params.coords = arguments[1];
2478 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2479 case glslang::EOpTextureQueryLevels:
2480 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002481 case glslang::EOpSparseTexelsResident:
2482 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002483 default:
2484 assert(0);
2485 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002486 }
John Kessenich140f3df2015-06-26 16:58:36 -06002487 }
2488
Rex Xufc618912015-09-09 16:42:49 +08002489 // Check for image functions other than queries
2490 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002491 std::vector<spv::Id> operands;
2492 auto opIt = arguments.begin();
2493 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002494
2495 // Handle subpass operations
2496 // TODO: GLSL should change to have the "MS" only on the type rather than the
2497 // built-in function.
2498 if (cracked.subpass) {
2499 // add on the (0,0) coordinate
2500 spv::Id zero = builder.makeIntConstant(0);
2501 std::vector<spv::Id> comps;
2502 comps.push_back(zero);
2503 comps.push_back(zero);
2504 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2505 if (sampler.ms) {
2506 operands.push_back(spv::ImageOperandsSampleMask);
2507 operands.push_back(*(opIt++));
2508 }
2509 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2510 }
2511
John Kessenich56bab042015-09-16 10:54:31 -06002512 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002513 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002514 if (sampler.ms) {
2515 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002516 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002517 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002518 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2519 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002520 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002521 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002522 if (sampler.ms) {
2523 operands.push_back(*(opIt + 1));
2524 operands.push_back(spv::ImageOperandsSampleMask);
2525 operands.push_back(*opIt);
2526 } else
2527 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002528 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002529 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2530 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002531 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002532 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2533 builder.addCapability(spv::CapabilitySparseResidency);
2534 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2535 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2536
2537 if (sampler.ms) {
2538 operands.push_back(spv::ImageOperandsSampleMask);
2539 operands.push_back(*opIt++);
2540 }
2541
2542 // Create the return type that was a special structure
2543 spv::Id texelOut = *opIt;
2544 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2545 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2546 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2547
2548 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2549
2550 // Decode the return type
2551 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2552 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002553 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002554 // Process image atomic operations
2555
2556 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2557 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002558 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002559
Rex Xufc618912015-09-09 16:42:49 +08002560 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002561 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002562
2563 std::vector<spv::Id> operands;
2564 operands.push_back(pointer);
2565 for (; opIt != arguments.end(); ++opIt)
2566 operands.push_back(*opIt);
2567
Rex Xu04db3f52015-09-16 11:44:02 +08002568 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002569 }
2570 }
2571
2572 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002573 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002574 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2575
John Kessenichfc51d282015-08-19 13:34:18 -06002576 // check for bias argument
2577 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002578 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002579 int nonBiasArgCount = 2;
2580 if (cracked.offset)
2581 ++nonBiasArgCount;
2582 if (cracked.grad)
2583 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002584 if (cracked.lodClamp)
2585 ++nonBiasArgCount;
2586 if (sparse)
2587 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002588
2589 if ((int)arguments.size() > nonBiasArgCount)
2590 bias = true;
2591 }
2592
John Kessenicha5c33d62016-06-02 23:45:21 -06002593 // See if the sampler param should really be just the SPV image part
2594 if (cracked.fetch) {
2595 // a fetch needs to have the image extracted first
2596 if (builder.isSampledImage(params.sampler))
2597 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2598 }
2599
John Kessenichfc51d282015-08-19 13:34:18 -06002600 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002601
John Kessenichfc51d282015-08-19 13:34:18 -06002602 params.coords = arguments[1];
2603 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002604 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002605
2606 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002607 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002608 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002609 ++extraArgs;
2610 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002611 params.Dref = arguments[2];
2612 ++extraArgs;
2613 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002614 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002615 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002616 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002617 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002618 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002619 dRefComp = builder.getNumComponents(params.coords) - 1;
2620 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002621 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2622 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002623
2624 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002625 if (cracked.lod) {
2626 params.lod = arguments[2];
2627 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002628 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2629 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2630 noImplicitLod = true;
2631 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002632
2633 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002634 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002635 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002636 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002637 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002638
2639 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002640 if (cracked.grad) {
2641 params.gradX = arguments[2 + extraArgs];
2642 params.gradY = arguments[3 + extraArgs];
2643 extraArgs += 2;
2644 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002645
2646 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002647 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002648 params.offset = arguments[2 + extraArgs];
2649 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002650 } else if (cracked.offsets) {
2651 params.offsets = arguments[2 + extraArgs];
2652 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002653 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002654
2655 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002656 if (cracked.lodClamp) {
2657 params.lodClamp = arguments[2 + extraArgs];
2658 ++extraArgs;
2659 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002660
2661 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002662 if (sparse) {
2663 params.texelOut = arguments[2 + extraArgs];
2664 ++extraArgs;
2665 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002666
2667 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002668 if (bias) {
2669 params.bias = arguments[2 + extraArgs];
2670 ++extraArgs;
2671 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002672
2673 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002674 if (cracked.gather && ! sampler.shadow) {
2675 // default component is 0, if missing, otherwise an argument
2676 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002677 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002678 ++extraArgs;
2679 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002680 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002681 }
2682 }
John Kessenichfc51d282015-08-19 13:34:18 -06002683
John Kessenich65336482016-06-16 14:06:26 -06002684 // projective component (might not to move)
2685 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2686 // are divided by the last component of P."
2687 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2688 // unused components will appear after all used components."
2689 if (cracked.proj) {
2690 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2691 int projTargetComp;
2692 switch (sampler.dim) {
2693 case glslang::Esd1D: projTargetComp = 1; break;
2694 case glslang::Esd2D: projTargetComp = 2; break;
2695 case glslang::EsdRect: projTargetComp = 2; break;
2696 default: projTargetComp = projSourceComp; break;
2697 }
2698 // copy the projective coordinate if we have to
2699 if (projTargetComp != projSourceComp) {
2700 spv::Id projComp = builder.createCompositeExtract(params.coords,
2701 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2702 projSourceComp);
2703 params.coords = builder.createCompositeInsert(projComp, params.coords,
2704 builder.getTypeId(params.coords), projTargetComp);
2705 }
2706 }
2707
John Kessenich019f08f2016-02-15 15:40:42 -07002708 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002709}
2710
2711spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2712{
2713 // Grab the function's pointer from the previously created function
2714 spv::Function* function = functionMap[node->getName().c_str()];
2715 if (! function)
2716 return 0;
2717
2718 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2719 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2720
2721 // See comments in makeFunctions() for details about the semantics for parameter passing.
2722 //
2723 // These imply we need a four step process:
2724 // 1. Evaluate the arguments
2725 // 2. Allocate and make copies of in, out, and inout arguments
2726 // 3. Make the call
2727 // 4. Copy back the results
2728
2729 // 1. Evaluate the arguments
2730 std::vector<spv::Builder::AccessChain> lValues;
2731 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002732 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002733 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002734 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002735 // build l-value
2736 builder.clearAccessChain();
2737 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002738 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002739 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2740 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002741 // save l-value
2742 lValues.push_back(builder.getAccessChain());
2743 } else {
2744 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002745 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002746 }
2747 }
2748
2749 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2750 // copy the original into that space.
2751 //
2752 // Also, build up the list of actual arguments to pass in for the call
2753 int lValueCount = 0;
2754 int rValueCount = 0;
2755 std::vector<spv::Id> spvArgs;
2756 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002757 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002758 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002759 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002760 builder.setAccessChain(lValues[lValueCount]);
2761 arg = builder.accessChainGetLValue();
2762 ++lValueCount;
2763 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002764 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002765 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2766 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2767 // need to copy the input into output space
2768 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002769 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002770 builder.createStore(copy, arg);
2771 }
2772 ++lValueCount;
2773 } else {
2774 arg = rValues[rValueCount];
2775 ++rValueCount;
2776 }
2777 spvArgs.push_back(arg);
2778 }
2779
2780 // 3. Make the call.
2781 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002782 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002783
2784 // 4. Copy back out an "out" arguments.
2785 lValueCount = 0;
2786 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2787 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2788 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2789 spv::Id copy = builder.createLoad(spvArgs[a]);
2790 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002791 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002792 }
2793 ++lValueCount;
2794 }
2795 }
2796
2797 return result;
2798}
2799
2800// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002801spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2802 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002803 spv::Id typeId, spv::Id left, spv::Id right,
2804 glslang::TBasicType typeProxy, bool reduceComparison)
2805{
Rex Xu8ff43de2016-04-22 16:51:45 +08002806 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002807 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002808 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002809
2810 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002811 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002812 bool comparison = false;
2813
2814 switch (op) {
2815 case glslang::EOpAdd:
2816 case glslang::EOpAddAssign:
2817 if (isFloat)
2818 binOp = spv::OpFAdd;
2819 else
2820 binOp = spv::OpIAdd;
2821 break;
2822 case glslang::EOpSub:
2823 case glslang::EOpSubAssign:
2824 if (isFloat)
2825 binOp = spv::OpFSub;
2826 else
2827 binOp = spv::OpISub;
2828 break;
2829 case glslang::EOpMul:
2830 case glslang::EOpMulAssign:
2831 if (isFloat)
2832 binOp = spv::OpFMul;
2833 else
2834 binOp = spv::OpIMul;
2835 break;
2836 case glslang::EOpVectorTimesScalar:
2837 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002838 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002839 if (builder.isVector(right))
2840 std::swap(left, right);
2841 assert(builder.isScalar(right));
2842 needMatchingVectors = false;
2843 binOp = spv::OpVectorTimesScalar;
2844 } else
2845 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 break;
2847 case glslang::EOpVectorTimesMatrix:
2848 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002849 binOp = spv::OpVectorTimesMatrix;
2850 break;
2851 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002852 binOp = spv::OpMatrixTimesVector;
2853 break;
2854 case glslang::EOpMatrixTimesScalar:
2855 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002856 binOp = spv::OpMatrixTimesScalar;
2857 break;
2858 case glslang::EOpMatrixTimesMatrix:
2859 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002860 binOp = spv::OpMatrixTimesMatrix;
2861 break;
2862 case glslang::EOpOuterProduct:
2863 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002864 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002865 break;
2866
2867 case glslang::EOpDiv:
2868 case glslang::EOpDivAssign:
2869 if (isFloat)
2870 binOp = spv::OpFDiv;
2871 else if (isUnsigned)
2872 binOp = spv::OpUDiv;
2873 else
2874 binOp = spv::OpSDiv;
2875 break;
2876 case glslang::EOpMod:
2877 case glslang::EOpModAssign:
2878 if (isFloat)
2879 binOp = spv::OpFMod;
2880 else if (isUnsigned)
2881 binOp = spv::OpUMod;
2882 else
2883 binOp = spv::OpSMod;
2884 break;
2885 case glslang::EOpRightShift:
2886 case glslang::EOpRightShiftAssign:
2887 if (isUnsigned)
2888 binOp = spv::OpShiftRightLogical;
2889 else
2890 binOp = spv::OpShiftRightArithmetic;
2891 break;
2892 case glslang::EOpLeftShift:
2893 case glslang::EOpLeftShiftAssign:
2894 binOp = spv::OpShiftLeftLogical;
2895 break;
2896 case glslang::EOpAnd:
2897 case glslang::EOpAndAssign:
2898 binOp = spv::OpBitwiseAnd;
2899 break;
2900 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002901 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002902 binOp = spv::OpLogicalAnd;
2903 break;
2904 case glslang::EOpInclusiveOr:
2905 case glslang::EOpInclusiveOrAssign:
2906 binOp = spv::OpBitwiseOr;
2907 break;
2908 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002909 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002910 binOp = spv::OpLogicalOr;
2911 break;
2912 case glslang::EOpExclusiveOr:
2913 case glslang::EOpExclusiveOrAssign:
2914 binOp = spv::OpBitwiseXor;
2915 break;
2916 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002917 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002919 break;
2920
2921 case glslang::EOpLessThan:
2922 case glslang::EOpGreaterThan:
2923 case glslang::EOpLessThanEqual:
2924 case glslang::EOpGreaterThanEqual:
2925 case glslang::EOpEqual:
2926 case glslang::EOpNotEqual:
2927 case glslang::EOpVectorEqual:
2928 case glslang::EOpVectorNotEqual:
2929 comparison = true;
2930 break;
2931 default:
2932 break;
2933 }
2934
John Kessenich7c1aa102015-10-15 13:29:11 -06002935 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002936 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002937 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002938 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002939 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002940
2941 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002942 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002943 builder.promoteScalar(precision, left, right);
2944
qining25262b32016-05-06 17:25:16 -04002945 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2946 addDecoration(result, noContraction);
2947 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002948 }
2949
2950 if (! comparison)
2951 return 0;
2952
John Kessenich7c1aa102015-10-15 13:29:11 -06002953 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002954
2955 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2956 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2957
John Kessenich22118352015-12-21 20:54:09 -07002958 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002959 }
2960
2961 switch (op) {
2962 case glslang::EOpLessThan:
2963 if (isFloat)
2964 binOp = spv::OpFOrdLessThan;
2965 else if (isUnsigned)
2966 binOp = spv::OpULessThan;
2967 else
2968 binOp = spv::OpSLessThan;
2969 break;
2970 case glslang::EOpGreaterThan:
2971 if (isFloat)
2972 binOp = spv::OpFOrdGreaterThan;
2973 else if (isUnsigned)
2974 binOp = spv::OpUGreaterThan;
2975 else
2976 binOp = spv::OpSGreaterThan;
2977 break;
2978 case glslang::EOpLessThanEqual:
2979 if (isFloat)
2980 binOp = spv::OpFOrdLessThanEqual;
2981 else if (isUnsigned)
2982 binOp = spv::OpULessThanEqual;
2983 else
2984 binOp = spv::OpSLessThanEqual;
2985 break;
2986 case glslang::EOpGreaterThanEqual:
2987 if (isFloat)
2988 binOp = spv::OpFOrdGreaterThanEqual;
2989 else if (isUnsigned)
2990 binOp = spv::OpUGreaterThanEqual;
2991 else
2992 binOp = spv::OpSGreaterThanEqual;
2993 break;
2994 case glslang::EOpEqual:
2995 case glslang::EOpVectorEqual:
2996 if (isFloat)
2997 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002998 else if (isBool)
2999 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003000 else
3001 binOp = spv::OpIEqual;
3002 break;
3003 case glslang::EOpNotEqual:
3004 case glslang::EOpVectorNotEqual:
3005 if (isFloat)
3006 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003007 else if (isBool)
3008 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003009 else
3010 binOp = spv::OpINotEqual;
3011 break;
3012 default:
3013 break;
3014 }
3015
qining25262b32016-05-06 17:25:16 -04003016 if (binOp != spv::OpNop) {
3017 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3018 addDecoration(result, noContraction);
3019 return builder.setPrecision(result, precision);
3020 }
John Kessenich140f3df2015-06-26 16:58:36 -06003021
3022 return 0;
3023}
3024
John Kessenich04bb8a02015-12-12 12:28:14 -07003025//
3026// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3027// These can be any of:
3028//
3029// matrix * scalar
3030// scalar * matrix
3031// matrix * matrix linear algebraic
3032// matrix * vector
3033// vector * matrix
3034// matrix * matrix componentwise
3035// matrix op matrix op in {+, -, /}
3036// matrix op scalar op in {+, -, /}
3037// scalar op matrix op in {+, -, /}
3038//
qining25262b32016-05-06 17:25:16 -04003039spv::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 -07003040{
3041 bool firstClass = true;
3042
3043 // First, handle first-class matrix operations (* and matrix/scalar)
3044 switch (op) {
3045 case spv::OpFDiv:
3046 if (builder.isMatrix(left) && builder.isScalar(right)) {
3047 // turn matrix / scalar into a multiply...
3048 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3049 op = spv::OpMatrixTimesScalar;
3050 } else
3051 firstClass = false;
3052 break;
3053 case spv::OpMatrixTimesScalar:
3054 if (builder.isMatrix(right))
3055 std::swap(left, right);
3056 assert(builder.isScalar(right));
3057 break;
3058 case spv::OpVectorTimesMatrix:
3059 assert(builder.isVector(left));
3060 assert(builder.isMatrix(right));
3061 break;
3062 case spv::OpMatrixTimesVector:
3063 assert(builder.isMatrix(left));
3064 assert(builder.isVector(right));
3065 break;
3066 case spv::OpMatrixTimesMatrix:
3067 assert(builder.isMatrix(left));
3068 assert(builder.isMatrix(right));
3069 break;
3070 default:
3071 firstClass = false;
3072 break;
3073 }
3074
qining25262b32016-05-06 17:25:16 -04003075 if (firstClass) {
3076 spv::Id result = builder.createBinOp(op, typeId, left, right);
3077 addDecoration(result, noContraction);
3078 return builder.setPrecision(result, precision);
3079 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003080
LoopDawg592860c2016-06-09 08:57:35 -06003081 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003082 // The result type of all of them is the same type as the (a) matrix operand.
3083 // The algorithm is to:
3084 // - break the matrix(es) into vectors
3085 // - smear any scalar to a vector
3086 // - do vector operations
3087 // - make a matrix out the vector results
3088 switch (op) {
3089 case spv::OpFAdd:
3090 case spv::OpFSub:
3091 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003092 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003093 case spv::OpFMul:
3094 {
3095 // one time set up...
3096 bool leftMat = builder.isMatrix(left);
3097 bool rightMat = builder.isMatrix(right);
3098 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3099 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3100 spv::Id scalarType = builder.getScalarTypeId(typeId);
3101 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3102 std::vector<spv::Id> results;
3103 spv::Id smearVec = spv::NoResult;
3104 if (builder.isScalar(left))
3105 smearVec = builder.smearScalar(precision, left, vecType);
3106 else if (builder.isScalar(right))
3107 smearVec = builder.smearScalar(precision, right, vecType);
3108
3109 // do each vector op
3110 for (unsigned int c = 0; c < numCols; ++c) {
3111 std::vector<unsigned int> indexes;
3112 indexes.push_back(c);
3113 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3114 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003115 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3116 addDecoration(result, noContraction);
3117 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003118 }
3119
3120 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003121 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003122 }
3123 default:
3124 assert(0);
3125 return spv::NoResult;
3126 }
3127}
3128
qining25262b32016-05-06 17:25:16 -04003129spv::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 -06003130{
3131 spv::Op unaryOp = spv::OpNop;
3132 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003133 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003134 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003135
3136 switch (op) {
3137 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003138 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003139 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003140 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003141 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003142 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003143 unaryOp = spv::OpSNegate;
3144 break;
3145
3146 case glslang::EOpLogicalNot:
3147 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003148 unaryOp = spv::OpLogicalNot;
3149 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003150 case glslang::EOpBitwiseNot:
3151 unaryOp = spv::OpNot;
3152 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003153
John Kessenich140f3df2015-06-26 16:58:36 -06003154 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003155 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160 case glslang::EOpTranspose:
3161 unaryOp = spv::OpTranspose;
3162 break;
3163
3164 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003171 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
3173 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003174 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 break;
3176 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003177 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003178 break;
3179 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003180 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003181 break;
3182 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003183 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003184 break;
3185 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003186 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 break;
3188
3189 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003197 break;
3198 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003200 break;
3201 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003202 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 break;
3204 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003205 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003206 break;
3207
3208 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003209 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003210 break;
3211 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003212 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003213 break;
3214
3215 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003216 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003217 break;
3218 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003219 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003220 break;
3221 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003222 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003223 break;
3224 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003225 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003226 break;
3227 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003228 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003229 break;
3230 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 break;
3233
3234 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003235 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003236 break;
3237 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003238 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003239 break;
3240 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003241 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003242 break;
3243 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003244 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003245 break;
3246 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003247 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003248 break;
3249 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003250 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003251 break;
3252
3253 case glslang::EOpIsNan:
3254 unaryOp = spv::OpIsNan;
3255 break;
3256 case glslang::EOpIsInf:
3257 unaryOp = spv::OpIsInf;
3258 break;
LoopDawg592860c2016-06-09 08:57:35 -06003259 case glslang::EOpIsFinite:
3260 unaryOp = spv::OpIsFinite;
3261 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003262
Rex Xucbc426e2015-12-15 16:03:10 +08003263 case glslang::EOpFloatBitsToInt:
3264 case glslang::EOpFloatBitsToUint:
3265 case glslang::EOpIntBitsToFloat:
3266 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003267 case glslang::EOpDoubleBitsToInt64:
3268 case glslang::EOpDoubleBitsToUint64:
3269 case glslang::EOpInt64BitsToDouble:
3270 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003271 unaryOp = spv::OpBitcast;
3272 break;
3273
John Kessenich140f3df2015-06-26 16:58:36 -06003274 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003275 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003276 break;
3277 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003278 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 break;
3280 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003281 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003282 break;
3283 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003284 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003285 break;
3286 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003287 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003288 break;
3289 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003290 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003291 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003292 case glslang::EOpPackSnorm4x8:
3293 libCall = spv::GLSLstd450PackSnorm4x8;
3294 break;
3295 case glslang::EOpUnpackSnorm4x8:
3296 libCall = spv::GLSLstd450UnpackSnorm4x8;
3297 break;
3298 case glslang::EOpPackUnorm4x8:
3299 libCall = spv::GLSLstd450PackUnorm4x8;
3300 break;
3301 case glslang::EOpUnpackUnorm4x8:
3302 libCall = spv::GLSLstd450UnpackUnorm4x8;
3303 break;
3304 case glslang::EOpPackDouble2x32:
3305 libCall = spv::GLSLstd450PackDouble2x32;
3306 break;
3307 case glslang::EOpUnpackDouble2x32:
3308 libCall = spv::GLSLstd450UnpackDouble2x32;
3309 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003310
Rex Xu8ff43de2016-04-22 16:51:45 +08003311 case glslang::EOpPackInt2x32:
3312 case glslang::EOpUnpackInt2x32:
3313 case glslang::EOpPackUint2x32:
3314 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003315 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003316 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3317 break;
3318
John Kessenich140f3df2015-06-26 16:58:36 -06003319 case glslang::EOpDPdx:
3320 unaryOp = spv::OpDPdx;
3321 break;
3322 case glslang::EOpDPdy:
3323 unaryOp = spv::OpDPdy;
3324 break;
3325 case glslang::EOpFwidth:
3326 unaryOp = spv::OpFwidth;
3327 break;
3328 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003329 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003330 unaryOp = spv::OpDPdxFine;
3331 break;
3332 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003333 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003334 unaryOp = spv::OpDPdyFine;
3335 break;
3336 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003337 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003338 unaryOp = spv::OpFwidthFine;
3339 break;
3340 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003341 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003342 unaryOp = spv::OpDPdxCoarse;
3343 break;
3344 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003345 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003346 unaryOp = spv::OpDPdyCoarse;
3347 break;
3348 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003349 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003350 unaryOp = spv::OpFwidthCoarse;
3351 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003352 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003353 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003354 libCall = spv::GLSLstd450InterpolateAtCentroid;
3355 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003356 case glslang::EOpAny:
3357 unaryOp = spv::OpAny;
3358 break;
3359 case glslang::EOpAll:
3360 unaryOp = spv::OpAll;
3361 break;
3362
3363 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003364 if (isFloat)
3365 libCall = spv::GLSLstd450FAbs;
3366 else
3367 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003368 break;
3369 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003370 if (isFloat)
3371 libCall = spv::GLSLstd450FSign;
3372 else
3373 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003374 break;
3375
John Kessenichfc51d282015-08-19 13:34:18 -06003376 case glslang::EOpAtomicCounterIncrement:
3377 case glslang::EOpAtomicCounterDecrement:
3378 case glslang::EOpAtomicCounter:
3379 {
3380 // Handle all of the atomics in one place, in createAtomicOperation()
3381 std::vector<spv::Id> operands;
3382 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003383 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003384 }
3385
John Kessenichfc51d282015-08-19 13:34:18 -06003386 case glslang::EOpBitFieldReverse:
3387 unaryOp = spv::OpBitReverse;
3388 break;
3389 case glslang::EOpBitCount:
3390 unaryOp = spv::OpBitCount;
3391 break;
3392 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003393 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003394 break;
3395 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003396 if (isUnsigned)
3397 libCall = spv::GLSLstd450FindUMsb;
3398 else
3399 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003400 break;
3401
Rex Xu574ab042016-04-14 16:53:07 +08003402 case glslang::EOpBallot:
3403 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003404 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003405 libCall = spv::GLSLstd450Bad;
3406 break;
3407
Rex Xu338b1852016-05-05 20:38:33 +08003408 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003409 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003410 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003411 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003412
John Kessenich140f3df2015-06-26 16:58:36 -06003413 default:
3414 return 0;
3415 }
3416
3417 spv::Id id;
3418 if (libCall >= 0) {
3419 std::vector<spv::Id> args;
3420 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003421 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003422 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003423 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003424 }
John Kessenich140f3df2015-06-26 16:58:36 -06003425
qining25262b32016-05-06 17:25:16 -04003426 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003427 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003428}
3429
John Kessenich7a53f762016-01-20 11:19:27 -07003430// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003431spv::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 -07003432{
3433 // Handle unary operations vector by vector.
3434 // The result type is the same type as the original type.
3435 // The algorithm is to:
3436 // - break the matrix into vectors
3437 // - apply the operation to each vector
3438 // - make a matrix out the vector results
3439
3440 // get the types sorted out
3441 int numCols = builder.getNumColumns(operand);
3442 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003443 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3444 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003445 std::vector<spv::Id> results;
3446
3447 // do each vector op
3448 for (int c = 0; c < numCols; ++c) {
3449 std::vector<unsigned int> indexes;
3450 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003451 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3452 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3453 addDecoration(destVec, noContraction);
3454 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003455 }
3456
3457 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003458 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003459}
3460
Rex Xu73e3ce72016-04-27 18:48:17 +08003461spv::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 -06003462{
3463 spv::Op convOp = spv::OpNop;
3464 spv::Id zero = 0;
3465 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003466 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003467
3468 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3469
3470 switch (op) {
3471 case glslang::EOpConvIntToBool:
3472 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003473 case glslang::EOpConvInt64ToBool:
3474 case glslang::EOpConvUint64ToBool:
3475 zero = (op == glslang::EOpConvInt64ToBool ||
3476 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003477 zero = makeSmearedConstant(zero, vectorSize);
3478 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3479
3480 case glslang::EOpConvFloatToBool:
3481 zero = builder.makeFloatConstant(0.0F);
3482 zero = makeSmearedConstant(zero, vectorSize);
3483 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3484
3485 case glslang::EOpConvDoubleToBool:
3486 zero = builder.makeDoubleConstant(0.0);
3487 zero = makeSmearedConstant(zero, vectorSize);
3488 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3489
3490 case glslang::EOpConvBoolToFloat:
3491 convOp = spv::OpSelect;
3492 zero = builder.makeFloatConstant(0.0);
3493 one = builder.makeFloatConstant(1.0);
3494 break;
3495 case glslang::EOpConvBoolToDouble:
3496 convOp = spv::OpSelect;
3497 zero = builder.makeDoubleConstant(0.0);
3498 one = builder.makeDoubleConstant(1.0);
3499 break;
3500 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003501 case glslang::EOpConvBoolToInt64:
3502 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3503 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003504 convOp = spv::OpSelect;
3505 break;
3506 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003507 case glslang::EOpConvBoolToUint64:
3508 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3509 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003510 convOp = spv::OpSelect;
3511 break;
3512
3513 case glslang::EOpConvIntToFloat:
3514 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003515 case glslang::EOpConvInt64ToFloat:
3516 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003517 convOp = spv::OpConvertSToF;
3518 break;
3519
3520 case glslang::EOpConvUintToFloat:
3521 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003522 case glslang::EOpConvUint64ToFloat:
3523 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003524 convOp = spv::OpConvertUToF;
3525 break;
3526
3527 case glslang::EOpConvDoubleToFloat:
3528 case glslang::EOpConvFloatToDouble:
3529 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003530 if (builder.isMatrixType(destType))
3531 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003532 break;
3533
3534 case glslang::EOpConvFloatToInt:
3535 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003536 case glslang::EOpConvFloatToInt64:
3537 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003538 convOp = spv::OpConvertFToS;
3539 break;
3540
3541 case glslang::EOpConvUintToInt:
3542 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003543 case glslang::EOpConvUint64ToInt64:
3544 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003545 if (builder.isInSpecConstCodeGenMode()) {
3546 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003547 zero = (op == glslang::EOpConvUintToInt64 ||
3548 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003549 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003550 // Use OpIAdd, instead of OpBitcast to do the conversion when
3551 // generating for OpSpecConstantOp instruction.
3552 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3553 }
3554 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003555 convOp = spv::OpBitcast;
3556 break;
3557
3558 case glslang::EOpConvFloatToUint:
3559 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003560 case glslang::EOpConvFloatToUint64:
3561 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003562 convOp = spv::OpConvertFToU;
3563 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003564
3565 case glslang::EOpConvIntToInt64:
3566 case glslang::EOpConvInt64ToInt:
3567 convOp = spv::OpSConvert;
3568 break;
3569
3570 case glslang::EOpConvUintToUint64:
3571 case glslang::EOpConvUint64ToUint:
3572 convOp = spv::OpUConvert;
3573 break;
3574
3575 case glslang::EOpConvIntToUint64:
3576 case glslang::EOpConvInt64ToUint:
3577 case glslang::EOpConvUint64ToInt:
3578 case glslang::EOpConvUintToInt64:
3579 // OpSConvert/OpUConvert + OpBitCast
3580 switch (op) {
3581 case glslang::EOpConvIntToUint64:
3582 convOp = spv::OpSConvert;
3583 type = builder.makeIntType(64);
3584 break;
3585 case glslang::EOpConvInt64ToUint:
3586 convOp = spv::OpSConvert;
3587 type = builder.makeIntType(32);
3588 break;
3589 case glslang::EOpConvUint64ToInt:
3590 convOp = spv::OpUConvert;
3591 type = builder.makeUintType(32);
3592 break;
3593 case glslang::EOpConvUintToInt64:
3594 convOp = spv::OpUConvert;
3595 type = builder.makeUintType(64);
3596 break;
3597 default:
3598 assert(0);
3599 break;
3600 }
3601
3602 if (vectorSize > 0)
3603 type = builder.makeVectorType(type, vectorSize);
3604
3605 operand = builder.createUnaryOp(convOp, type, operand);
3606
3607 if (builder.isInSpecConstCodeGenMode()) {
3608 // Build zero scalar or vector for OpIAdd.
3609 zero = (op == glslang::EOpConvIntToUint64 ||
3610 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3611 zero = makeSmearedConstant(zero, vectorSize);
3612 // Use OpIAdd, instead of OpBitcast to do the conversion when
3613 // generating for OpSpecConstantOp instruction.
3614 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3615 }
3616 // For normal run-time conversion instruction, use OpBitcast.
3617 convOp = spv::OpBitcast;
3618 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003619 default:
3620 break;
3621 }
3622
3623 spv::Id result = 0;
3624 if (convOp == spv::OpNop)
3625 return result;
3626
3627 if (convOp == spv::OpSelect) {
3628 zero = makeSmearedConstant(zero, vectorSize);
3629 one = makeSmearedConstant(one, vectorSize);
3630 result = builder.createTriOp(convOp, destType, operand, one, zero);
3631 } else
3632 result = builder.createUnaryOp(convOp, destType, operand);
3633
John Kessenich32cfd492016-02-02 12:37:46 -07003634 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003635}
3636
3637spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3638{
3639 if (vectorSize == 0)
3640 return constant;
3641
3642 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3643 std::vector<spv::Id> components;
3644 for (int c = 0; c < vectorSize; ++c)
3645 components.push_back(constant);
3646 return builder.makeCompositeConstant(vectorTypeId, components);
3647}
3648
John Kessenich426394d2015-07-23 10:22:48 -06003649// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003650spv::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 -06003651{
3652 spv::Op opCode = spv::OpNop;
3653
3654 switch (op) {
3655 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003656 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003657 opCode = spv::OpAtomicIAdd;
3658 break;
3659 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003660 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003661 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003662 break;
3663 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003664 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003665 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003666 break;
3667 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003668 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003669 opCode = spv::OpAtomicAnd;
3670 break;
3671 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003672 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003673 opCode = spv::OpAtomicOr;
3674 break;
3675 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003676 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003677 opCode = spv::OpAtomicXor;
3678 break;
3679 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003680 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003681 opCode = spv::OpAtomicExchange;
3682 break;
3683 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003684 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003685 opCode = spv::OpAtomicCompareExchange;
3686 break;
3687 case glslang::EOpAtomicCounterIncrement:
3688 opCode = spv::OpAtomicIIncrement;
3689 break;
3690 case glslang::EOpAtomicCounterDecrement:
3691 opCode = spv::OpAtomicIDecrement;
3692 break;
3693 case glslang::EOpAtomicCounter:
3694 opCode = spv::OpAtomicLoad;
3695 break;
3696 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003697 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003698 break;
3699 }
3700
3701 // Sort out the operands
3702 // - mapping from glslang -> SPV
3703 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003704 // - compare-exchange swaps the value and comparator
3705 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003706 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3707 auto opIt = operands.begin(); // walk the glslang operands
3708 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003709 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3710 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3711 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003712 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3713 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003714 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003715 spvAtomicOperands.push_back(*(opIt + 1));
3716 spvAtomicOperands.push_back(*opIt);
3717 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003718 }
John Kessenich426394d2015-07-23 10:22:48 -06003719
John Kessenich3e60a6f2015-09-14 22:45:16 -06003720 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003721 for (; opIt != operands.end(); ++opIt)
3722 spvAtomicOperands.push_back(*opIt);
3723
3724 return builder.createOp(opCode, typeId, spvAtomicOperands);
3725}
3726
John Kessenich91cef522016-05-05 16:45:40 -06003727// Create group invocation operations.
3728spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3729{
3730 builder.addCapability(spv::CapabilityGroups);
3731
3732 std::vector<spv::Id> operands;
3733 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3734 operands.push_back(operand);
3735
3736 switch (op) {
3737 case glslang::EOpAnyInvocation:
3738 case glslang::EOpAllInvocations:
3739 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3740
3741 case glslang::EOpAllInvocationsEqual:
3742 {
3743 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3744 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3745
3746 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3747 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3748 }
3749 default:
3750 logger->missingFunctionality("invocation operation");
3751 return spv::NoResult;
3752 }
3753}
3754
John Kessenich5e4b1242015-08-06 22:53:06 -06003755spv::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 -06003756{
Rex Xu8ff43de2016-04-22 16:51:45 +08003757 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3759
John Kessenich140f3df2015-06-26 16:58:36 -06003760 spv::Op opCode = spv::OpNop;
3761 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003762 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003763 spv::Id typeId0 = 0;
3764 if (consumedOperands > 0)
3765 typeId0 = builder.getTypeId(operands[0]);
3766 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003767
3768 switch (op) {
3769 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 if (isFloat)
3771 libCall = spv::GLSLstd450FMin;
3772 else if (isUnsigned)
3773 libCall = spv::GLSLstd450UMin;
3774 else
3775 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003776 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
3778 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003779 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003780 break;
3781 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003782 if (isFloat)
3783 libCall = spv::GLSLstd450FMax;
3784 else if (isUnsigned)
3785 libCall = spv::GLSLstd450UMax;
3786 else
3787 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003788 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003789 break;
3790 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003791 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003792 break;
3793 case glslang::EOpDot:
3794 opCode = spv::OpDot;
3795 break;
3796 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003798 break;
3799
3800 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003801 if (isFloat)
3802 libCall = spv::GLSLstd450FClamp;
3803 else if (isUnsigned)
3804 libCall = spv::GLSLstd450UClamp;
3805 else
3806 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003807 builder.promoteScalar(precision, operands.front(), operands[1]);
3808 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003809 break;
3810 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003811 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3812 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003813 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003814 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003815 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003816 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003817 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003818 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003822 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003823 break;
3824 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003825 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003826 builder.promoteScalar(precision, operands[0], operands[2]);
3827 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003828 break;
3829
3830 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003831 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003834 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003835 break;
3836 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003837 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003841 break;
3842 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003843 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003845 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003846 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003847 libCall = spv::GLSLstd450InterpolateAtSample;
3848 break;
3849 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003850 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003851 libCall = spv::GLSLstd450InterpolateAtOffset;
3852 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003853 case glslang::EOpAddCarry:
3854 opCode = spv::OpIAddCarry;
3855 typeId = builder.makeStructResultType(typeId0, typeId0);
3856 consumedOperands = 2;
3857 break;
3858 case glslang::EOpSubBorrow:
3859 opCode = spv::OpISubBorrow;
3860 typeId = builder.makeStructResultType(typeId0, typeId0);
3861 consumedOperands = 2;
3862 break;
3863 case glslang::EOpUMulExtended:
3864 opCode = spv::OpUMulExtended;
3865 typeId = builder.makeStructResultType(typeId0, typeId0);
3866 consumedOperands = 2;
3867 break;
3868 case glslang::EOpIMulExtended:
3869 opCode = spv::OpSMulExtended;
3870 typeId = builder.makeStructResultType(typeId0, typeId0);
3871 consumedOperands = 2;
3872 break;
3873 case glslang::EOpBitfieldExtract:
3874 if (isUnsigned)
3875 opCode = spv::OpBitFieldUExtract;
3876 else
3877 opCode = spv::OpBitFieldSExtract;
3878 break;
3879 case glslang::EOpBitfieldInsert:
3880 opCode = spv::OpBitFieldInsert;
3881 break;
3882
3883 case glslang::EOpFma:
3884 libCall = spv::GLSLstd450Fma;
3885 break;
3886 case glslang::EOpFrexp:
3887 libCall = spv::GLSLstd450FrexpStruct;
3888 if (builder.getNumComponents(operands[0]) == 1)
3889 frexpIntType = builder.makeIntegerType(32, true);
3890 else
3891 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3892 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3893 consumedOperands = 1;
3894 break;
3895 case glslang::EOpLdexp:
3896 libCall = spv::GLSLstd450Ldexp;
3897 break;
3898
Rex Xu574ab042016-04-14 16:53:07 +08003899 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003900 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003901 libCall = spv::GLSLstd450Bad;
3902 break;
3903
John Kessenich140f3df2015-06-26 16:58:36 -06003904 default:
3905 return 0;
3906 }
3907
3908 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003909 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003910 // Use an extended instruction from the standard library.
3911 // Construct the call arguments, without modifying the original operands vector.
3912 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3913 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003914 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003915 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003916 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003917 case 0:
3918 // should all be handled by visitAggregate and createNoArgOperation
3919 assert(0);
3920 return 0;
3921 case 1:
3922 // should all be handled by createUnaryOperation
3923 assert(0);
3924 return 0;
3925 case 2:
3926 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3927 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003928 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003929 // anything 3 or over doesn't have l-value operands, so all should be consumed
3930 assert(consumedOperands == operands.size());
3931 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003932 break;
3933 }
3934 }
3935
John Kessenich55e7d112015-11-15 21:33:39 -07003936 // Decode the return types that were structures
3937 switch (op) {
3938 case glslang::EOpAddCarry:
3939 case glslang::EOpSubBorrow:
3940 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3941 id = builder.createCompositeExtract(id, typeId0, 0);
3942 break;
3943 case glslang::EOpUMulExtended:
3944 case glslang::EOpIMulExtended:
3945 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3946 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3947 break;
3948 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003949 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003950 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3951 id = builder.createCompositeExtract(id, typeId0, 0);
3952 break;
3953 default:
3954 break;
3955 }
3956
John Kessenich32cfd492016-02-02 12:37:46 -07003957 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003958}
3959
3960// Intrinsics with no arguments, no return value, and no precision.
3961spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3962{
3963 // TODO: get the barrier operands correct
3964
3965 switch (op) {
3966 case glslang::EOpEmitVertex:
3967 builder.createNoResultOp(spv::OpEmitVertex);
3968 return 0;
3969 case glslang::EOpEndPrimitive:
3970 builder.createNoResultOp(spv::OpEndPrimitive);
3971 return 0;
3972 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003973 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003974 return 0;
3975 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003976 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003977 return 0;
3978 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003980 return 0;
3981 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003982 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003983 return 0;
3984 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003985 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003986 return 0;
3987 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003988 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003989 return 0;
3990 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003991 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003992 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06003993 case glslang::EOpAllMemoryBarrierWithGroupSync:
3994 // Control barrier with non-"None" semantic is also a memory barrier.
3995 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3996 return 0;
3997 case glslang::EOpGroupMemoryBarrierWithGroupSync:
3998 // Control barrier with non-"None" semantic is also a memory barrier.
3999 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4000 return 0;
4001 case glslang::EOpWorkgroupMemoryBarrier:
4002 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4003 return 0;
4004 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4005 // Control barrier with non-"None" semantic is also a memory barrier.
4006 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4007 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004008 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004009 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004010 return 0;
4011 }
4012}
4013
4014spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4015{
John Kessenich2f273362015-07-18 22:34:27 -06004016 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004017 spv::Id id;
4018 if (symbolValues.end() != iter) {
4019 id = iter->second;
4020 return id;
4021 }
4022
4023 // it was not found, create it
4024 id = createSpvVariable(symbol);
4025 symbolValues[symbol->getId()] = id;
4026
4027 if (! symbol->getType().isStruct()) {
4028 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004029 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004030 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004031 if (symbol->getType().getQualifier().hasSpecConstantId())
4032 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004033 if (symbol->getQualifier().hasIndex())
4034 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4035 if (symbol->getQualifier().hasComponent())
4036 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4037 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004038 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004039 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004040 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004041 if (symbol->getQualifier().hasXfbBuffer())
4042 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4043 if (symbol->getQualifier().hasXfbOffset())
4044 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4045 }
4046 }
4047
scygan2c864272016-05-18 18:09:17 +02004048 if (symbol->getQualifier().hasLocation())
4049 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004050 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004051 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004052 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004053 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004054 }
John Kessenich140f3df2015-06-26 16:58:36 -06004055 if (symbol->getQualifier().hasSet())
4056 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004057 else if (IsDescriptorResource(symbol->getType())) {
4058 // default to 0
4059 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4060 }
John Kessenich140f3df2015-06-26 16:58:36 -06004061 if (symbol->getQualifier().hasBinding())
4062 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004063 if (symbol->getQualifier().hasAttachment())
4064 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004065 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004066 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004067 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004069 if (symbol->getQualifier().hasXfbBuffer())
4070 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4071 }
4072
Rex Xu1da878f2016-02-21 20:59:01 +08004073 if (symbol->getType().isImage()) {
4074 std::vector<spv::Decoration> memory;
4075 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4076 for (unsigned int i = 0; i < memory.size(); ++i)
4077 addDecoration(id, memory[i]);
4078 }
4079
John Kessenich140f3df2015-06-26 16:58:36 -06004080 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004081 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004082 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004083 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004084
John Kessenich140f3df2015-06-26 16:58:36 -06004085 return id;
4086}
4087
John Kessenich55e7d112015-11-15 21:33:39 -07004088// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004089void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4090{
4091 if (dec != spv::BadValue)
4092 builder.addDecoration(id, dec);
4093}
4094
John Kessenich55e7d112015-11-15 21:33:39 -07004095// If 'dec' is valid, add a one-operand decoration to an object
4096void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4097{
4098 if (dec != spv::BadValue)
4099 builder.addDecoration(id, dec, value);
4100}
4101
4102// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004103void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4104{
4105 if (dec != spv::BadValue)
4106 builder.addMemberDecoration(id, (unsigned)member, dec);
4107}
4108
John Kessenich92187592016-02-01 13:45:25 -07004109// If 'dec' is valid, add a one-operand decoration to a struct member
4110void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4111{
4112 if (dec != spv::BadValue)
4113 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4114}
4115
John Kessenich55e7d112015-11-15 21:33:39 -07004116// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004117// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004118//
4119// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4120//
4121// Recursively walk the nodes. The nodes form a tree whose leaves are
4122// regular constants, which themselves are trees that createSpvConstant()
4123// recursively walks. So, this function walks the "top" of the tree:
4124// - emit specialization constant-building instructions for specConstant
4125// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004126spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004127{
John Kessenich7cc0e282016-03-20 00:46:02 -06004128 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004129
qining4f4bb812016-04-03 23:55:17 -04004130 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004131 if (! node.getQualifier().specConstant) {
4132 // hand off to the non-spec-constant path
4133 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4134 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004135 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004136 nextConst, false);
4137 }
4138
4139 // We now know we have a specialization constant to build
4140
John Kessenichd94c0032016-05-30 19:29:40 -06004141 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004142 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4143 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4144 std::vector<spv::Id> dimConstId;
4145 for (int dim = 0; dim < 3; ++dim) {
4146 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4147 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4148 if (specConst)
4149 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4150 }
4151 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4152 }
4153
4154 // An AST node labelled as specialization constant should be a symbol node.
4155 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4156 if (auto* sn = node.getAsSymbolNode()) {
4157 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004158 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4159 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4160 // will set the builder into spec constant op instruction generating mode.
4161 sub_tree->traverse(this);
4162 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004163 } else if (auto* const_union_array = &sn->getConstArray()){
4164 int nextConst = 0;
4165 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004166 }
4167 }
qining4f4bb812016-04-03 23:55:17 -04004168
4169 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4170 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004171 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004172 exit(1);
4173 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004174}
4175
John Kessenich140f3df2015-06-26 16:58:36 -06004176// Use 'consts' as the flattened glslang source of scalar constants to recursively
4177// build the aggregate SPIR-V constant.
4178//
4179// If there are not enough elements present in 'consts', 0 will be substituted;
4180// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4181//
qining08408382016-03-21 09:51:37 -04004182spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004183{
4184 // vector of constants for SPIR-V
4185 std::vector<spv::Id> spvConsts;
4186
4187 // Type is used for struct and array constants
4188 spv::Id typeId = convertGlslangToSpvType(glslangType);
4189
4190 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004191 glslang::TType elementType(glslangType, 0);
4192 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004193 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004194 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004195 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004196 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004197 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004198 } else if (glslangType.getStruct()) {
4199 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4200 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004201 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004202 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004203 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4204 bool zero = nextConst >= consts.size();
4205 switch (glslangType.getBasicType()) {
4206 case glslang::EbtInt:
4207 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4208 break;
4209 case glslang::EbtUint:
4210 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4211 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004212 case glslang::EbtInt64:
4213 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4214 break;
4215 case glslang::EbtUint64:
4216 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4217 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004218 case glslang::EbtFloat:
4219 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4220 break;
4221 case glslang::EbtDouble:
4222 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4223 break;
4224 case glslang::EbtBool:
4225 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4226 break;
4227 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004228 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004229 break;
4230 }
4231 ++nextConst;
4232 }
4233 } else {
4234 // we have a non-aggregate (scalar) constant
4235 bool zero = nextConst >= consts.size();
4236 spv::Id scalar = 0;
4237 switch (glslangType.getBasicType()) {
4238 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004239 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004240 break;
4241 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004242 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004243 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004244 case glslang::EbtInt64:
4245 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4246 break;
4247 case glslang::EbtUint64:
4248 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4249 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004250 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004251 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004252 break;
4253 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004254 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004255 break;
4256 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004257 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004258 break;
4259 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004260 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004261 break;
4262 }
4263 ++nextConst;
4264 return scalar;
4265 }
4266
4267 return builder.makeCompositeConstant(typeId, spvConsts);
4268}
4269
John Kessenich7c1aa102015-10-15 13:29:11 -06004270// Return true if the node is a constant or symbol whose reading has no
4271// non-trivial observable cost or effect.
4272bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4273{
4274 // don't know what this is
4275 if (node == nullptr)
4276 return false;
4277
4278 // a constant is safe
4279 if (node->getAsConstantUnion() != nullptr)
4280 return true;
4281
4282 // not a symbol means non-trivial
4283 if (node->getAsSymbolNode() == nullptr)
4284 return false;
4285
4286 // a symbol, depends on what's being read
4287 switch (node->getType().getQualifier().storage) {
4288 case glslang::EvqTemporary:
4289 case glslang::EvqGlobal:
4290 case glslang::EvqIn:
4291 case glslang::EvqInOut:
4292 case glslang::EvqConst:
4293 case glslang::EvqConstReadOnly:
4294 case glslang::EvqUniform:
4295 return true;
4296 default:
4297 return false;
4298 }
qining25262b32016-05-06 17:25:16 -04004299}
John Kessenich7c1aa102015-10-15 13:29:11 -06004300
4301// A node is trivial if it is a single operation with no side effects.
4302// Error on the side of saying non-trivial.
4303// Return true if trivial.
4304bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4305{
4306 if (node == nullptr)
4307 return false;
4308
4309 // symbols and constants are trivial
4310 if (isTrivialLeaf(node))
4311 return true;
4312
4313 // otherwise, it needs to be a simple operation or one or two leaf nodes
4314
4315 // not a simple operation
4316 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4317 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4318 if (binaryNode == nullptr && unaryNode == nullptr)
4319 return false;
4320
4321 // not on leaf nodes
4322 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4323 return false;
4324
4325 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4326 return false;
4327 }
4328
4329 switch (node->getAsOperator()->getOp()) {
4330 case glslang::EOpLogicalNot:
4331 case glslang::EOpConvIntToBool:
4332 case glslang::EOpConvUintToBool:
4333 case glslang::EOpConvFloatToBool:
4334 case glslang::EOpConvDoubleToBool:
4335 case glslang::EOpEqual:
4336 case glslang::EOpNotEqual:
4337 case glslang::EOpLessThan:
4338 case glslang::EOpGreaterThan:
4339 case glslang::EOpLessThanEqual:
4340 case glslang::EOpGreaterThanEqual:
4341 case glslang::EOpIndexDirect:
4342 case glslang::EOpIndexDirectStruct:
4343 case glslang::EOpLogicalXor:
4344 case glslang::EOpAny:
4345 case glslang::EOpAll:
4346 return true;
4347 default:
4348 return false;
4349 }
4350}
4351
4352// Emit short-circuiting code, where 'right' is never evaluated unless
4353// the left side is true (for &&) or false (for ||).
4354spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4355{
4356 spv::Id boolTypeId = builder.makeBoolType();
4357
4358 // emit left operand
4359 builder.clearAccessChain();
4360 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004361 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004362
4363 // Operands to accumulate OpPhi operands
4364 std::vector<spv::Id> phiOperands;
4365 // accumulate left operand's phi information
4366 phiOperands.push_back(leftId);
4367 phiOperands.push_back(builder.getBuildPoint()->getId());
4368
4369 // Make the two kinds of operation symmetric with a "!"
4370 // || => emit "if (! left) result = right"
4371 // && => emit "if ( left) result = right"
4372 //
4373 // TODO: this runtime "not" for || could be avoided by adding functionality
4374 // to 'builder' to have an "else" without an "then"
4375 if (op == glslang::EOpLogicalOr)
4376 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4377
4378 // make an "if" based on the left value
4379 spv::Builder::If ifBuilder(leftId, builder);
4380
4381 // emit right operand as the "then" part of the "if"
4382 builder.clearAccessChain();
4383 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004384 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004385
4386 // accumulate left operand's phi information
4387 phiOperands.push_back(rightId);
4388 phiOperands.push_back(builder.getBuildPoint()->getId());
4389
4390 // finish the "if"
4391 ifBuilder.makeEndIf();
4392
4393 // phi together the two results
4394 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4395}
4396
John Kessenich140f3df2015-06-26 16:58:36 -06004397}; // end anonymous namespace
4398
4399namespace glslang {
4400
John Kessenich68d78fd2015-07-12 19:28:10 -06004401void GetSpirvVersion(std::string& version)
4402{
John Kessenich9e55f632015-07-15 10:03:39 -06004403 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004404 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004405 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004406 version = buf;
4407}
4408
John Kessenich140f3df2015-06-26 16:58:36 -06004409// Write SPIR-V out to a binary file
4410void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4411{
4412 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004413 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004414 for (int i = 0; i < (int)spirv.size(); ++i) {
4415 unsigned int word = spirv[i];
4416 out.write((const char*)&word, 4);
4417 }
4418 out.close();
4419}
4420
4421//
4422// Set up the glslang traversal
4423//
4424void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4425{
Lei Zhang17535f72016-05-04 15:55:59 -04004426 spv::SpvBuildLogger logger;
4427 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004428}
4429
Lei Zhang17535f72016-05-04 15:55:59 -04004430void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004431{
John Kessenich140f3df2015-06-26 16:58:36 -06004432 TIntermNode* root = intermediate.getTreeRoot();
4433
4434 if (root == 0)
4435 return;
4436
4437 glslang::GetThreadPoolAllocator().push();
4438
Lei Zhang17535f72016-05-04 15:55:59 -04004439 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004440
4441 root->traverse(&it);
4442
4443 it.dumpSpv(spirv);
4444
4445 glslang::GetThreadPoolAllocator().pop();
4446}
4447
4448}; // end namespace glslang