blob: 0324468cb3558fdd7d198d076d572981a7a26079 [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;
241 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
242 } 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
646 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
647 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400648 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || 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:
1408 noReturnValue = true;
1409 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1410 break;
1411
John Kessenich426394d2015-07-23 10:22:48 -06001412 case glslang::EOpAtomicAdd:
1413 case glslang::EOpAtomicMin:
1414 case glslang::EOpAtomicMax:
1415 case glslang::EOpAtomicAnd:
1416 case glslang::EOpAtomicOr:
1417 case glslang::EOpAtomicXor:
1418 case glslang::EOpAtomicExchange:
1419 case glslang::EOpAtomicCompSwap:
1420 atomic = true;
1421 break;
1422
John Kessenich140f3df2015-06-26 16:58:36 -06001423 default:
1424 break;
1425 }
1426
1427 //
1428 // See if it maps to a regular operation.
1429 //
John Kessenich140f3df2015-06-26 16:58:36 -06001430 if (binOp != glslang::EOpNull) {
1431 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1432 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1433 assert(left && right);
1434
1435 builder.clearAccessChain();
1436 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001437 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 builder.clearAccessChain();
1440 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001441 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001442
qining25262b32016-05-06 17:25:16 -04001443 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1444 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001445 left->getType().getBasicType(), reduceComparison);
1446
1447 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001448 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001449 builder.clearAccessChain();
1450 builder.setAccessChainRValue(result);
1451
1452 return false;
1453 }
1454
John Kessenich426394d2015-07-23 10:22:48 -06001455 //
1456 // Create the list of operands.
1457 //
John Kessenich140f3df2015-06-26 16:58:36 -06001458 glslang::TIntermSequence& glslangOperands = node->getSequence();
1459 std::vector<spv::Id> operands;
1460 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1461 builder.clearAccessChain();
1462 glslangOperands[arg]->traverse(this);
1463
1464 // special case l-value operands; there are just a few
1465 bool lvalue = false;
1466 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001467 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001468 case glslang::EOpModf:
1469 if (arg == 1)
1470 lvalue = true;
1471 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001472 case glslang::EOpInterpolateAtSample:
1473 case glslang::EOpInterpolateAtOffset:
1474 if (arg == 0)
1475 lvalue = true;
1476 break;
Rex Xud4782c12015-09-06 16:30:11 +08001477 case glslang::EOpAtomicAdd:
1478 case glslang::EOpAtomicMin:
1479 case glslang::EOpAtomicMax:
1480 case glslang::EOpAtomicAnd:
1481 case glslang::EOpAtomicOr:
1482 case glslang::EOpAtomicXor:
1483 case glslang::EOpAtomicExchange:
1484 case glslang::EOpAtomicCompSwap:
1485 if (arg == 0)
1486 lvalue = true;
1487 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001488 case glslang::EOpAddCarry:
1489 case glslang::EOpSubBorrow:
1490 if (arg == 2)
1491 lvalue = true;
1492 break;
1493 case glslang::EOpUMulExtended:
1494 case glslang::EOpIMulExtended:
1495 if (arg >= 2)
1496 lvalue = true;
1497 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001498 default:
1499 break;
1500 }
1501 if (lvalue)
1502 operands.push_back(builder.accessChainGetLValue());
1503 else
John Kessenich32cfd492016-02-02 12:37:46 -07001504 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001505 }
John Kessenich426394d2015-07-23 10:22:48 -06001506
1507 if (atomic) {
1508 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001509 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001510 } else {
1511 // Pass through to generic operations.
1512 switch (glslangOperands.size()) {
1513 case 0:
1514 result = createNoArgOperation(node->getOp());
1515 break;
1516 case 1:
qining25262b32016-05-06 17:25:16 -04001517 result = createUnaryOperation(
1518 node->getOp(), precision,
1519 TranslateNoContractionDecoration(node->getType().getQualifier()),
1520 convertGlslangToSpvType(node->getType()), operands.front(),
1521 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001522 break;
1523 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001524 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001525 break;
1526 }
John Kessenich140f3df2015-06-26 16:58:36 -06001527 }
1528
1529 if (noReturnValue)
1530 return false;
1531
1532 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001533 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001534 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001535 } else {
1536 builder.clearAccessChain();
1537 builder.setAccessChainRValue(result);
1538 return false;
1539 }
1540}
1541
1542bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1543{
1544 // This path handles both if-then-else and ?:
1545 // The if-then-else has a node type of void, while
1546 // ?: has a non-void node type
1547 spv::Id result = 0;
1548 if (node->getBasicType() != glslang::EbtVoid) {
1549 // don't handle this as just on-the-fly temporaries, because there will be two names
1550 // and better to leave SSA to later passes
1551 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1552 }
1553
1554 // emit the condition before doing anything with selection
1555 node->getCondition()->traverse(this);
1556
1557 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001558 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001559
1560 if (node->getTrueBlock()) {
1561 // emit the "then" statement
1562 node->getTrueBlock()->traverse(this);
1563 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001564 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001565 }
1566
1567 if (node->getFalseBlock()) {
1568 ifBuilder.makeBeginElse();
1569 // emit the "else" statement
1570 node->getFalseBlock()->traverse(this);
1571 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001572 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001573 }
1574
1575 ifBuilder.makeEndIf();
1576
1577 if (result) {
1578 // GLSL only has r-values as the result of a :?, but
1579 // if we have an l-value, that can be more efficient if it will
1580 // become the base of a complex r-value expression, because the
1581 // next layer copies r-values into memory to use the access-chain mechanism
1582 builder.clearAccessChain();
1583 builder.setAccessChainLValue(result);
1584 }
1585
1586 return false;
1587}
1588
1589bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1590{
1591 // emit and get the condition before doing anything with switch
1592 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001593 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001594
1595 // browse the children to sort out code segments
1596 int defaultSegment = -1;
1597 std::vector<TIntermNode*> codeSegments;
1598 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1599 std::vector<int> caseValues;
1600 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1601 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1602 TIntermNode* child = *c;
1603 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001604 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001605 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001606 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001607 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1608 } else
1609 codeSegments.push_back(child);
1610 }
1611
qining25262b32016-05-06 17:25:16 -04001612 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001613 // statements between the last case and the end of the switch statement
1614 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1615 (int)codeSegments.size() == defaultSegment)
1616 codeSegments.push_back(nullptr);
1617
1618 // make the switch statement
1619 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001620 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001621
1622 // emit all the code in the segments
1623 breakForLoop.push(false);
1624 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1625 builder.nextSwitchSegment(segmentBlocks, s);
1626 if (codeSegments[s])
1627 codeSegments[s]->traverse(this);
1628 else
1629 builder.addSwitchBreak();
1630 }
1631 breakForLoop.pop();
1632
1633 builder.endSwitch(segmentBlocks);
1634
1635 return false;
1636}
1637
1638void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1639{
1640 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001641 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001642
1643 builder.clearAccessChain();
1644 builder.setAccessChainRValue(constant);
1645}
1646
1647bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1648{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001649 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001650 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001651 // Spec requires back edges to target header blocks, and every header block
1652 // must dominate its merge block. Make a header block first to ensure these
1653 // conditions are met. By definition, it will contain OpLoopMerge, followed
1654 // by a block-ending branch. But we don't want to put any other body/test
1655 // instructions in it, since the body/test may have arbitrary instructions,
1656 // including merges of its own.
1657 builder.setBuildPoint(&blocks.head);
1658 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001659 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001660 spv::Block& test = builder.makeNewBlock();
1661 builder.createBranch(&test);
1662
1663 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001664 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001665 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001666 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001667 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1668
1669 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001670 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001672 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001674 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001675
1676 builder.setBuildPoint(&blocks.continue_target);
1677 if (node->getTerminal())
1678 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001679 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001680 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001681 builder.createBranch(&blocks.body);
1682
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001683 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001684 builder.setBuildPoint(&blocks.body);
1685 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001686 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001687 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001688 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001689
1690 builder.setBuildPoint(&blocks.continue_target);
1691 if (node->getTerminal())
1692 node->getTerminal()->traverse(this);
1693 if (node->getTest()) {
1694 node->getTest()->traverse(this);
1695 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001696 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001697 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001698 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001699 // TODO: unless there was a break/return/discard instruction
1700 // somewhere in the body, this is an infinite loop, so we should
1701 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001702 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001703 }
John Kessenich140f3df2015-06-26 16:58:36 -06001704 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001705 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001706 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001707 return false;
1708}
1709
1710bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1711{
1712 if (node->getExpression())
1713 node->getExpression()->traverse(this);
1714
1715 switch (node->getFlowOp()) {
1716 case glslang::EOpKill:
1717 builder.makeDiscard();
1718 break;
1719 case glslang::EOpBreak:
1720 if (breakForLoop.top())
1721 builder.createLoopExit();
1722 else
1723 builder.addSwitchBreak();
1724 break;
1725 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001726 builder.createLoopContinue();
1727 break;
1728 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001729 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001730 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001731 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001732 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001733
1734 builder.clearAccessChain();
1735 break;
1736
1737 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001738 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 break;
1740 }
1741
1742 return false;
1743}
1744
1745spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1746{
qining25262b32016-05-06 17:25:16 -04001747 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001748 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001749 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001750 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001751 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001752 }
1753
1754 // Now, handle actual variables
1755 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1756 spv::Id spvType = convertGlslangToSpvType(node->getType());
1757
1758 const char* name = node->getName().c_str();
1759 if (glslang::IsAnonymous(name))
1760 name = "";
1761
1762 return builder.createVariable(storageClass, spvType, name);
1763}
1764
1765// Return type Id of the sampled type.
1766spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1767{
1768 switch (sampler.type) {
1769 case glslang::EbtFloat: return builder.makeFloatType(32);
1770 case glslang::EbtInt: return builder.makeIntType(32);
1771 case glslang::EbtUint: return builder.makeUintType(32);
1772 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001773 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001774 return builder.makeFloatType(32);
1775 }
1776}
1777
John Kessenich3ac051e2015-12-20 11:29:16 -07001778// Convert from a glslang type to an SPV type, by calling into a
1779// recursive version of this function. This establishes the inherited
1780// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001781spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1782{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001783 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001784}
1785
1786// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001787// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001788spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001789{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001790 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001791
1792 switch (type.getBasicType()) {
1793 case glslang::EbtVoid:
1794 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001795 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001796 break;
1797 case glslang::EbtFloat:
1798 spvType = builder.makeFloatType(32);
1799 break;
1800 case glslang::EbtDouble:
1801 spvType = builder.makeFloatType(64);
1802 break;
1803 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001804 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1805 // a 32-bit int where non-0 means true.
1806 if (explicitLayout != glslang::ElpNone)
1807 spvType = builder.makeUintType(32);
1808 else
1809 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001810 break;
1811 case glslang::EbtInt:
1812 spvType = builder.makeIntType(32);
1813 break;
1814 case glslang::EbtUint:
1815 spvType = builder.makeUintType(32);
1816 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001817 case glslang::EbtInt64:
1818 builder.addCapability(spv::CapabilityInt64);
1819 spvType = builder.makeIntType(64);
1820 break;
1821 case glslang::EbtUint64:
1822 builder.addCapability(spv::CapabilityInt64);
1823 spvType = builder.makeUintType(64);
1824 break;
John Kessenich426394d2015-07-23 10:22:48 -06001825 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001826 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 -06001827 spvType = builder.makeUintType(32);
1828 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001829 case glslang::EbtSampler:
1830 {
1831 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001832 if (sampler.sampler) {
1833 // pure sampler
1834 spvType = builder.makeSamplerType();
1835 } else {
1836 // an image is present, make its type
1837 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1838 sampler.image ? 2 : 1, TranslateImageFormat(type));
1839 if (sampler.combined) {
1840 // already has both image and sampler, make the combined type
1841 spvType = builder.makeSampledImageType(spvType);
1842 }
John Kessenich55e7d112015-11-15 21:33:39 -07001843 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001844 }
John Kessenich140f3df2015-06-26 16:58:36 -06001845 break;
1846 case glslang::EbtStruct:
1847 case glslang::EbtBlock:
1848 {
1849 // If we've seen this struct type, return it
1850 const glslang::TTypeList* glslangStruct = type.getStruct();
1851 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001852
1853 // Try to share structs for different layouts, but not yet for other
1854 // kinds of qualification (primarily not yet including interpolant qualification).
1855 if (! HasNonLayoutQualifiers(qualifier))
1856 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1857 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001858 break;
1859
1860 // else, we haven't seen it...
1861
1862 // Create a vector of struct types for SPIR-V to consume
1863 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1864 if (type.getBasicType() == glslang::EbtBlock)
1865 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001866 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001867 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1868 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1869 if (glslangType.hiddenMember()) {
1870 ++memberDelta;
1871 if (type.getBasicType() == glslang::EbtBlock)
1872 memberRemapper[glslangStruct][i] = -1;
1873 } else {
1874 if (type.getBasicType() == glslang::EbtBlock)
1875 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001876 // modify just this child's view of the qualifier
1877 glslang::TQualifier subQualifier = glslangType.getQualifier();
1878 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001879
1880 // manually inherit location; it's more complex
1881 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1882 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1883 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001884 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001885
1886 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001887 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001888 }
1889 }
1890
1891 // Make the SPIR-V type
1892 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 if (! HasNonLayoutQualifiers(qualifier))
1894 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001895
1896 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001897 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001898 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001899 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1900 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1901 int member = i;
1902 if (type.getBasicType() == glslang::EbtBlock)
1903 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001904
John Kesseniche0b6cad2015-12-24 10:30:13 -07001905 // modify just this child's view of the qualifier
1906 glslang::TQualifier subQualifier = glslangType.getQualifier();
1907 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001908
John Kessenich140f3df2015-06-26 16:58:36 -06001909 // using -1 above to indicate a hidden member
1910 if (member >= 0) {
1911 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001912 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001913 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001914 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001915 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001916 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
Rex Xubbceed72016-05-21 09:40:44 +08001917 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
scygan8add1512016-05-06 16:54:54 +02001918 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001919 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001920
Rex Xu1da878f2016-02-21 20:59:01 +08001921 if (qualifier.storage == glslang::EvqBuffer) {
1922 std::vector<spv::Decoration> memory;
1923 TranslateMemoryDecoration(subQualifier, memory);
1924 for (unsigned int i = 0; i < memory.size(); ++i)
1925 addMemberDecoration(spvType, member, memory[i]);
1926 }
1927
John Kessenich09677482016-02-19 12:21:50 -07001928 // compute location decoration; tricky based on whether inheritance is at play
1929 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1930 // probably move to the linker stage of the front end proper, and just have the
1931 // answer sitting already distributed throughout the individual member locations.
1932 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001933 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001934 // struct members should not have explicit locations
1935 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001936 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001937 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001938 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1939 // The members, and their nested types, must not themselves have Location decorations.
1940 }
John Kessenich09677482016-02-19 12:21:50 -07001941 else if (qualifier.hasLocation()) // inheritance
1942 location = qualifier.layoutLocation + locationOffset;
1943 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001944 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001945 if (location >= 0)
1946 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1947
1948 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001949 if (glslangType.getQualifier().hasComponent())
1950 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1951 if (glslangType.getQualifier().hasXfbOffset())
1952 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001953 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001954 // figure out what to do with offset, which is accumulating
1955 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001956 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001957 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001958 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001959 offset = nextOffset;
1960 }
John Kessenich140f3df2015-06-26 16:58:36 -06001961
John Kessenichf85e8062015-12-19 13:57:10 -07001962 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001963 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001964
John Kessenich140f3df2015-06-26 16:58:36 -06001965 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001966 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001967 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001968 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001969 }
1970 }
1971
1972 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001973 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001974 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001975 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001976 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001977 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001978 }
John Kessenich140f3df2015-06-26 16:58:36 -06001979 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001980 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001981 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001982 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001983 if (type.getQualifier().hasXfbBuffer())
1984 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1985 }
1986 }
1987 break;
1988 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001989 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001990 break;
1991 }
1992
1993 if (type.isMatrix())
1994 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1995 else {
1996 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1997 if (type.getVectorSize() > 1)
1998 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1999 }
2000
2001 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002002 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2003
John Kessenichc9a80832015-09-12 12:17:44 -06002004 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002005 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002006 // We need to decorate array strides for types needing explicit layout, except blocks.
2007 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002008 // Use a dummy glslang type for querying internal strides of
2009 // arrays of arrays, but using just a one-dimensional array.
2010 glslang::TType simpleArrayType(type, 0); // deference type of the array
2011 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2012 simpleArrayType.getArraySizes().dereference();
2013
2014 // Will compute the higher-order strides here, rather than making a whole
2015 // pile of types and doing repetitive recursion on their contents.
2016 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2017 }
John Kessenichf8842e52016-01-04 19:22:56 -07002018
2019 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002020 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002021 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002022 if (stride > 0)
2023 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002024 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002025 }
2026 } else {
2027 // single-dimensional array, and don't yet have stride
2028
John Kessenichf8842e52016-01-04 19:22:56 -07002029 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002030 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2031 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002032 }
John Kessenich31ed4832015-09-09 17:51:38 -06002033
John Kessenichc9a80832015-09-12 12:17:44 -06002034 // Do the outer dimension, which might not be known for a runtime-sized array
2035 if (type.isRuntimeSizedArray()) {
2036 spvType = builder.makeRuntimeArray(spvType);
2037 } else {
2038 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002039 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002040 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002041 if (stride > 0)
2042 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002043 }
2044
2045 return spvType;
2046}
2047
John Kessenich6c292d32016-02-15 20:58:50 -07002048// Turn the expression forming the array size into an id.
2049// This is not quite trivial, because of specialization constants.
2050// Sometimes, a raw constant is turned into an Id, and sometimes
2051// a specialization constant expression is.
2052spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2053{
2054 // First, see if this is sized with a node, meaning a specialization constant:
2055 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2056 if (specNode != nullptr) {
2057 builder.clearAccessChain();
2058 specNode->traverse(this);
2059 return accessChainLoad(specNode->getAsTyped()->getType());
2060 }
qining25262b32016-05-06 17:25:16 -04002061
John Kessenich6c292d32016-02-15 20:58:50 -07002062 // Otherwise, need a compile-time (front end) size, get it:
2063 int size = arraySizes.getDimSize(dim);
2064 assert(size > 0);
2065 return builder.makeUintConstant(size);
2066}
2067
John Kessenich103bef92016-02-08 21:38:15 -07002068// Wrap the builder's accessChainLoad to:
2069// - localize handling of RelaxedPrecision
2070// - use the SPIR-V inferred type instead of another conversion of the glslang type
2071// (avoids unnecessary work and possible type punning for structures)
2072// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002073spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2074{
John Kessenich103bef92016-02-08 21:38:15 -07002075 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2076 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2077
2078 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002079 if (type.getBasicType() == glslang::EbtBool) {
2080 if (builder.isScalarType(nominalTypeId)) {
2081 // Conversion for bool
2082 spv::Id boolType = builder.makeBoolType();
2083 if (nominalTypeId != boolType)
2084 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2085 } else if (builder.isVectorType(nominalTypeId)) {
2086 // Conversion for bvec
2087 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2088 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2089 if (nominalTypeId != bvecType)
2090 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2091 }
2092 }
John Kessenich103bef92016-02-08 21:38:15 -07002093
2094 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002095}
2096
Rex Xu27253232016-02-23 17:51:09 +08002097// Wrap the builder's accessChainStore to:
2098// - do conversion of concrete to abstract type
2099void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2100{
2101 // Need to convert to abstract types when necessary
2102 if (type.getBasicType() == glslang::EbtBool) {
2103 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2104
2105 if (builder.isScalarType(nominalTypeId)) {
2106 // Conversion for bool
2107 spv::Id boolType = builder.makeBoolType();
2108 if (nominalTypeId != boolType) {
2109 spv::Id zero = builder.makeUintConstant(0);
2110 spv::Id one = builder.makeUintConstant(1);
2111 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2112 }
2113 } else if (builder.isVectorType(nominalTypeId)) {
2114 // Conversion for bvec
2115 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2116 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2117 if (nominalTypeId != bvecType) {
2118 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2119 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2120 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2121 }
2122 }
2123 }
2124
2125 builder.accessChainStore(rvalue);
2126}
2127
John Kessenichf85e8062015-12-19 13:57:10 -07002128// Decide whether or not this type should be
2129// decorated with offsets and strides, and if so
2130// whether std140 or std430 rules should be applied.
2131glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002132{
John Kessenichf85e8062015-12-19 13:57:10 -07002133 // has to be a block
2134 if (type.getBasicType() != glslang::EbtBlock)
2135 return glslang::ElpNone;
2136
2137 // has to be a uniform or buffer block
2138 if (type.getQualifier().storage != glslang::EvqUniform &&
2139 type.getQualifier().storage != glslang::EvqBuffer)
2140 return glslang::ElpNone;
2141
2142 // return the layout to use
2143 switch (type.getQualifier().layoutPacking) {
2144 case glslang::ElpStd140:
2145 case glslang::ElpStd430:
2146 return type.getQualifier().layoutPacking;
2147 default:
2148 return glslang::ElpNone;
2149 }
John Kessenich31ed4832015-09-09 17:51:38 -06002150}
2151
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002152// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002153int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002154{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002155 int size;
John Kessenich49987892015-12-29 17:11:44 -07002156 int stride;
2157 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002158
2159 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002160}
2161
John Kessenich49987892015-12-29 17:11:44 -07002162// 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 -07002163// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002164int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002165{
John Kessenich49987892015-12-29 17:11:44 -07002166 glslang::TType elementType;
2167 elementType.shallowCopy(matrixType);
2168 elementType.clearArraySizes();
2169
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002170 int size;
John Kessenich49987892015-12-29 17:11:44 -07002171 int stride;
2172 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2173
2174 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002175}
2176
John Kessenich5e4b1242015-08-06 22:53:06 -06002177// Given a member type of a struct, realign the current offset for it, and compute
2178// the next (not yet aligned) offset for the next member, which will get aligned
2179// on the next call.
2180// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2181// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2182// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002183void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002184 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002185{
2186 // this will get a positive value when deemed necessary
2187 nextOffset = -1;
2188
John Kessenich5e4b1242015-08-06 22:53:06 -06002189 // override anything in currentOffset with user-set offset
2190 if (memberType.getQualifier().hasOffset())
2191 currentOffset = memberType.getQualifier().layoutOffset;
2192
2193 // It could be that current linker usage in glslang updated all the layoutOffset,
2194 // in which case the following code does not matter. But, that's not quite right
2195 // once cross-compilation unit GLSL validation is done, as the original user
2196 // settings are needed in layoutOffset, and then the following will come into play.
2197
John Kessenichf85e8062015-12-19 13:57:10 -07002198 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002199 if (! memberType.getQualifier().hasOffset())
2200 currentOffset = -1;
2201
2202 return;
2203 }
2204
John Kessenichf85e8062015-12-19 13:57:10 -07002205 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002206 if (currentOffset < 0)
2207 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002208
John Kessenich5e4b1242015-08-06 22:53:06 -06002209 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2210 // but possibly not yet correctly aligned.
2211
2212 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002213 int dummyStride;
2214 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002215 glslang::RoundToPow2(currentOffset, memberAlignment);
2216 nextOffset = currentOffset + memberSize;
2217}
2218
David Netoa901ffe2016-06-08 14:11:40 +01002219void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002220{
David Netoa901ffe2016-06-08 14:11:40 +01002221 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2222 switch (glslangBuiltIn)
2223 {
2224 case glslang::EbvClipDistance:
2225 case glslang::EbvCullDistance:
2226 case glslang::EbvPointSize:
2227 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2228 // Alternately, we could just call this for any glslang built-in, since the
2229 // capability already guards against duplicates.
2230 TranslateBuiltInDecoration(glslangBuiltIn, false);
2231 break;
2232 default:
2233 // Capabilities were already generated when the struct was declared.
2234 break;
2235 }
John Kessenichebb50532016-05-16 19:22:05 -06002236}
2237
John Kessenich140f3df2015-06-26 16:58:36 -06002238bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2239{
John Kessenich4d65ee32016-03-12 18:17:47 -07002240 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002241 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002242 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002243}
2244
2245// Make all the functions, skeletally, without actually visiting their bodies.
2246void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2247{
2248 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2249 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2250 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2251 continue;
2252
2253 // We're on a user function. Set up the basic interface for the function now,
2254 // so that it's available to call.
2255 // Translating the body will happen later.
2256 //
qining25262b32016-05-06 17:25:16 -04002257 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002258 // function. What it is an address of varies:
2259 //
2260 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2261 // so that write needs to be to a copy, hence the address of a copy works.
2262 //
2263 // - "const in" parameters can just be the r-value, as no writes need occur.
2264 //
2265 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2266 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2267
2268 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002269 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002270 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2271
2272 for (int p = 0; p < (int)parameters.size(); ++p) {
2273 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2274 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002275 if (paramType.isOpaque())
2276 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2277 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002278 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2279 else
2280 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002281 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002282 paramTypes.push_back(typeId);
2283 }
2284
2285 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002286 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2287 convertGlslangToSpvType(glslFunction->getType()),
2288 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002289
2290 // Track function to emit/call later
2291 functionMap[glslFunction->getName().c_str()] = function;
2292
2293 // Set the parameter id's
2294 for (int p = 0; p < (int)parameters.size(); ++p) {
2295 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2296 // give a name too
2297 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2298 }
2299 }
2300}
2301
2302// Process all the initializers, while skipping the functions and link objects
2303void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2304{
2305 builder.setBuildPoint(shaderEntry->getLastBlock());
2306 for (int i = 0; i < (int)initializers.size(); ++i) {
2307 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2308 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2309
2310 // We're on a top-level node that's not a function. Treat as an initializer, whose
2311 // code goes into the beginning of main.
2312 initializer->traverse(this);
2313 }
2314 }
2315}
2316
2317// Process all the functions, while skipping initializers.
2318void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2319{
2320 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2321 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2322 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2323 node->traverse(this);
2324 }
2325}
2326
2327void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2328{
qining25262b32016-05-06 17:25:16 -04002329 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002330 // that called makeFunctions().
2331 spv::Function* function = functionMap[node->getName().c_str()];
2332 spv::Block* functionBlock = function->getEntryBlock();
2333 builder.setBuildPoint(functionBlock);
2334}
2335
Rex Xu04db3f52015-09-16 11:44:02 +08002336void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002337{
Rex Xufc618912015-09-09 16:42:49 +08002338 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002339
2340 glslang::TSampler sampler = {};
2341 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002342 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002343 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2344 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2345 }
2346
John Kessenich140f3df2015-06-26 16:58:36 -06002347 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2348 builder.clearAccessChain();
2349 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002350
2351 // Special case l-value operands
2352 bool lvalue = false;
2353 switch (node.getOp()) {
2354 case glslang::EOpImageAtomicAdd:
2355 case glslang::EOpImageAtomicMin:
2356 case glslang::EOpImageAtomicMax:
2357 case glslang::EOpImageAtomicAnd:
2358 case glslang::EOpImageAtomicOr:
2359 case glslang::EOpImageAtomicXor:
2360 case glslang::EOpImageAtomicExchange:
2361 case glslang::EOpImageAtomicCompSwap:
2362 if (i == 0)
2363 lvalue = true;
2364 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002365 case glslang::EOpSparseImageLoad:
2366 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2367 lvalue = true;
2368 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002369 case glslang::EOpSparseTexture:
2370 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2371 lvalue = true;
2372 break;
2373 case glslang::EOpSparseTextureClamp:
2374 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2375 lvalue = true;
2376 break;
2377 case glslang::EOpSparseTextureLod:
2378 case glslang::EOpSparseTextureOffset:
2379 if (i == 3)
2380 lvalue = true;
2381 break;
2382 case glslang::EOpSparseTextureFetch:
2383 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2384 lvalue = true;
2385 break;
2386 case glslang::EOpSparseTextureFetchOffset:
2387 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2388 lvalue = true;
2389 break;
2390 case glslang::EOpSparseTextureLodOffset:
2391 case glslang::EOpSparseTextureGrad:
2392 case glslang::EOpSparseTextureOffsetClamp:
2393 if (i == 4)
2394 lvalue = true;
2395 break;
2396 case glslang::EOpSparseTextureGradOffset:
2397 case glslang::EOpSparseTextureGradClamp:
2398 if (i == 5)
2399 lvalue = true;
2400 break;
2401 case glslang::EOpSparseTextureGradOffsetClamp:
2402 if (i == 6)
2403 lvalue = true;
2404 break;
2405 case glslang::EOpSparseTextureGather:
2406 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2407 lvalue = true;
2408 break;
2409 case glslang::EOpSparseTextureGatherOffset:
2410 case glslang::EOpSparseTextureGatherOffsets:
2411 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2412 lvalue = true;
2413 break;
Rex Xufc618912015-09-09 16:42:49 +08002414 default:
2415 break;
2416 }
2417
Rex Xu6b86d492015-09-16 17:48:22 +08002418 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002419 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002420 else
John Kessenich32cfd492016-02-02 12:37:46 -07002421 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002422 }
2423}
2424
John Kessenichfc51d282015-08-19 13:34:18 -06002425void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002426{
John Kessenichfc51d282015-08-19 13:34:18 -06002427 builder.clearAccessChain();
2428 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002429 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002430}
John Kessenich140f3df2015-06-26 16:58:36 -06002431
John Kessenichfc51d282015-08-19 13:34:18 -06002432spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2433{
Rex Xufc618912015-09-09 16:42:49 +08002434 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002435 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002436 }
2437
John Kessenichfc51d282015-08-19 13:34:18 -06002438 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002439 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2440 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2441 std::vector<spv::Id> arguments;
2442 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002443 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002444 else
2445 translateArguments(*node->getAsUnaryNode(), arguments);
2446 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2447
2448 spv::Builder::TextureParameters params = { };
2449 params.sampler = arguments[0];
2450
Rex Xu04db3f52015-09-16 11:44:02 +08002451 glslang::TCrackedTextureOp cracked;
2452 node->crackTexture(sampler, cracked);
2453
John Kessenichfc51d282015-08-19 13:34:18 -06002454 // Check for queries
2455 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002456 // a sampled image needs to have the image extracted first
2457 if (builder.isSampledImage(params.sampler))
2458 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002459 switch (node->getOp()) {
2460 case glslang::EOpImageQuerySize:
2461 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002462 if (arguments.size() > 1) {
2463 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002464 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002465 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002466 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002467 case glslang::EOpImageQuerySamples:
2468 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002469 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002470 case glslang::EOpTextureQueryLod:
2471 params.coords = arguments[1];
2472 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2473 case glslang::EOpTextureQueryLevels:
2474 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002475 case glslang::EOpSparseTexelsResident:
2476 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002477 default:
2478 assert(0);
2479 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002480 }
John Kessenich140f3df2015-06-26 16:58:36 -06002481 }
2482
Rex Xufc618912015-09-09 16:42:49 +08002483 // Check for image functions other than queries
2484 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002485 std::vector<spv::Id> operands;
2486 auto opIt = arguments.begin();
2487 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002488
2489 // Handle subpass operations
2490 // TODO: GLSL should change to have the "MS" only on the type rather than the
2491 // built-in function.
2492 if (cracked.subpass) {
2493 // add on the (0,0) coordinate
2494 spv::Id zero = builder.makeIntConstant(0);
2495 std::vector<spv::Id> comps;
2496 comps.push_back(zero);
2497 comps.push_back(zero);
2498 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2499 if (sampler.ms) {
2500 operands.push_back(spv::ImageOperandsSampleMask);
2501 operands.push_back(*(opIt++));
2502 }
2503 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2504 }
2505
John Kessenich56bab042015-09-16 10:54:31 -06002506 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002507 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002508 if (sampler.ms) {
2509 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002510 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002511 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002512 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2513 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002514 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002515 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002516 if (sampler.ms) {
2517 operands.push_back(*(opIt + 1));
2518 operands.push_back(spv::ImageOperandsSampleMask);
2519 operands.push_back(*opIt);
2520 } else
2521 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002522 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002523 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2524 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002525 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002526 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2527 builder.addCapability(spv::CapabilitySparseResidency);
2528 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2529 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2530
2531 if (sampler.ms) {
2532 operands.push_back(spv::ImageOperandsSampleMask);
2533 operands.push_back(*opIt++);
2534 }
2535
2536 // Create the return type that was a special structure
2537 spv::Id texelOut = *opIt;
2538 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2539 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2540 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2541
2542 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2543
2544 // Decode the return type
2545 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2546 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002547 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002548 // Process image atomic operations
2549
2550 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2551 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002552 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002553
Rex Xufc618912015-09-09 16:42:49 +08002554 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002555 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002556
2557 std::vector<spv::Id> operands;
2558 operands.push_back(pointer);
2559 for (; opIt != arguments.end(); ++opIt)
2560 operands.push_back(*opIt);
2561
Rex Xu04db3f52015-09-16 11:44:02 +08002562 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002563 }
2564 }
2565
2566 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002567 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002568 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2569
John Kessenichfc51d282015-08-19 13:34:18 -06002570 // check for bias argument
2571 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002572 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002573 int nonBiasArgCount = 2;
2574 if (cracked.offset)
2575 ++nonBiasArgCount;
2576 if (cracked.grad)
2577 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002578 if (cracked.lodClamp)
2579 ++nonBiasArgCount;
2580 if (sparse)
2581 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002582
2583 if ((int)arguments.size() > nonBiasArgCount)
2584 bias = true;
2585 }
2586
John Kessenicha5c33d62016-06-02 23:45:21 -06002587 // See if the sampler param should really be just the SPV image part
2588 if (cracked.fetch) {
2589 // a fetch needs to have the image extracted first
2590 if (builder.isSampledImage(params.sampler))
2591 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2592 }
2593
John Kessenichfc51d282015-08-19 13:34:18 -06002594 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002595
John Kessenichfc51d282015-08-19 13:34:18 -06002596 params.coords = arguments[1];
2597 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002598 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002599
2600 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002601 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002602 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002603 ++extraArgs;
2604 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002605 params.Dref = arguments[2];
2606 ++extraArgs;
2607 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002608 std::vector<spv::Id> indexes;
2609 int comp;
2610 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002611 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002612 else
2613 comp = builder.getNumComponents(params.coords) - 1;
2614 indexes.push_back(comp);
2615 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2616 }
2617 if (cracked.lod) {
2618 params.lod = arguments[2];
2619 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002620 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2621 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2622 noImplicitLod = true;
2623 }
2624 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002625 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002626 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002627 }
2628 if (cracked.grad) {
2629 params.gradX = arguments[2 + extraArgs];
2630 params.gradY = arguments[3 + extraArgs];
2631 extraArgs += 2;
2632 }
John Kessenich55e7d112015-11-15 21:33:39 -07002633 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002634 params.offset = arguments[2 + extraArgs];
2635 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002636 } else if (cracked.offsets) {
2637 params.offsets = arguments[2 + extraArgs];
2638 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002639 }
Rex Xu48edadf2015-12-31 16:11:41 +08002640 if (cracked.lodClamp) {
2641 params.lodClamp = arguments[2 + extraArgs];
2642 ++extraArgs;
2643 }
2644 if (sparse) {
2645 params.texelOut = arguments[2 + extraArgs];
2646 ++extraArgs;
2647 }
John Kessenichfc51d282015-08-19 13:34:18 -06002648 if (bias) {
2649 params.bias = arguments[2 + extraArgs];
2650 ++extraArgs;
2651 }
John Kessenich55e7d112015-11-15 21:33:39 -07002652 if (cracked.gather && ! sampler.shadow) {
2653 // default component is 0, if missing, otherwise an argument
2654 if (2 + extraArgs < (int)arguments.size()) {
2655 params.comp = arguments[2 + extraArgs];
2656 ++extraArgs;
2657 } else {
2658 params.comp = builder.makeIntConstant(0);
2659 }
2660 }
John Kessenichfc51d282015-08-19 13:34:18 -06002661
John Kessenich019f08f2016-02-15 15:40:42 -07002662 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002663}
2664
2665spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2666{
2667 // Grab the function's pointer from the previously created function
2668 spv::Function* function = functionMap[node->getName().c_str()];
2669 if (! function)
2670 return 0;
2671
2672 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2673 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2674
2675 // See comments in makeFunctions() for details about the semantics for parameter passing.
2676 //
2677 // These imply we need a four step process:
2678 // 1. Evaluate the arguments
2679 // 2. Allocate and make copies of in, out, and inout arguments
2680 // 3. Make the call
2681 // 4. Copy back the results
2682
2683 // 1. Evaluate the arguments
2684 std::vector<spv::Builder::AccessChain> lValues;
2685 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002686 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002688 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002689 // build l-value
2690 builder.clearAccessChain();
2691 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002692 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002693 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2694 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002695 // save l-value
2696 lValues.push_back(builder.getAccessChain());
2697 } else {
2698 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002699 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002700 }
2701 }
2702
2703 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2704 // copy the original into that space.
2705 //
2706 // Also, build up the list of actual arguments to pass in for the call
2707 int lValueCount = 0;
2708 int rValueCount = 0;
2709 std::vector<spv::Id> spvArgs;
2710 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002711 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002712 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002713 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002714 builder.setAccessChain(lValues[lValueCount]);
2715 arg = builder.accessChainGetLValue();
2716 ++lValueCount;
2717 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002718 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002719 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2720 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2721 // need to copy the input into output space
2722 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002723 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002724 builder.createStore(copy, arg);
2725 }
2726 ++lValueCount;
2727 } else {
2728 arg = rValues[rValueCount];
2729 ++rValueCount;
2730 }
2731 spvArgs.push_back(arg);
2732 }
2733
2734 // 3. Make the call.
2735 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002736 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002737
2738 // 4. Copy back out an "out" arguments.
2739 lValueCount = 0;
2740 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2741 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2742 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2743 spv::Id copy = builder.createLoad(spvArgs[a]);
2744 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002745 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002746 }
2747 ++lValueCount;
2748 }
2749 }
2750
2751 return result;
2752}
2753
2754// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002755spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2756 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002757 spv::Id typeId, spv::Id left, spv::Id right,
2758 glslang::TBasicType typeProxy, bool reduceComparison)
2759{
Rex Xu8ff43de2016-04-22 16:51:45 +08002760 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002761 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002762 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002763
2764 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002765 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002766 bool comparison = false;
2767
2768 switch (op) {
2769 case glslang::EOpAdd:
2770 case glslang::EOpAddAssign:
2771 if (isFloat)
2772 binOp = spv::OpFAdd;
2773 else
2774 binOp = spv::OpIAdd;
2775 break;
2776 case glslang::EOpSub:
2777 case glslang::EOpSubAssign:
2778 if (isFloat)
2779 binOp = spv::OpFSub;
2780 else
2781 binOp = spv::OpISub;
2782 break;
2783 case glslang::EOpMul:
2784 case glslang::EOpMulAssign:
2785 if (isFloat)
2786 binOp = spv::OpFMul;
2787 else
2788 binOp = spv::OpIMul;
2789 break;
2790 case glslang::EOpVectorTimesScalar:
2791 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002792 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002793 if (builder.isVector(right))
2794 std::swap(left, right);
2795 assert(builder.isScalar(right));
2796 needMatchingVectors = false;
2797 binOp = spv::OpVectorTimesScalar;
2798 } else
2799 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002800 break;
2801 case glslang::EOpVectorTimesMatrix:
2802 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002803 binOp = spv::OpVectorTimesMatrix;
2804 break;
2805 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002806 binOp = spv::OpMatrixTimesVector;
2807 break;
2808 case glslang::EOpMatrixTimesScalar:
2809 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002810 binOp = spv::OpMatrixTimesScalar;
2811 break;
2812 case glslang::EOpMatrixTimesMatrix:
2813 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002814 binOp = spv::OpMatrixTimesMatrix;
2815 break;
2816 case glslang::EOpOuterProduct:
2817 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002818 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002819 break;
2820
2821 case glslang::EOpDiv:
2822 case glslang::EOpDivAssign:
2823 if (isFloat)
2824 binOp = spv::OpFDiv;
2825 else if (isUnsigned)
2826 binOp = spv::OpUDiv;
2827 else
2828 binOp = spv::OpSDiv;
2829 break;
2830 case glslang::EOpMod:
2831 case glslang::EOpModAssign:
2832 if (isFloat)
2833 binOp = spv::OpFMod;
2834 else if (isUnsigned)
2835 binOp = spv::OpUMod;
2836 else
2837 binOp = spv::OpSMod;
2838 break;
2839 case glslang::EOpRightShift:
2840 case glslang::EOpRightShiftAssign:
2841 if (isUnsigned)
2842 binOp = spv::OpShiftRightLogical;
2843 else
2844 binOp = spv::OpShiftRightArithmetic;
2845 break;
2846 case glslang::EOpLeftShift:
2847 case glslang::EOpLeftShiftAssign:
2848 binOp = spv::OpShiftLeftLogical;
2849 break;
2850 case glslang::EOpAnd:
2851 case glslang::EOpAndAssign:
2852 binOp = spv::OpBitwiseAnd;
2853 break;
2854 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002855 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002856 binOp = spv::OpLogicalAnd;
2857 break;
2858 case glslang::EOpInclusiveOr:
2859 case glslang::EOpInclusiveOrAssign:
2860 binOp = spv::OpBitwiseOr;
2861 break;
2862 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002863 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002864 binOp = spv::OpLogicalOr;
2865 break;
2866 case glslang::EOpExclusiveOr:
2867 case glslang::EOpExclusiveOrAssign:
2868 binOp = spv::OpBitwiseXor;
2869 break;
2870 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002871 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002872 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002873 break;
2874
2875 case glslang::EOpLessThan:
2876 case glslang::EOpGreaterThan:
2877 case glslang::EOpLessThanEqual:
2878 case glslang::EOpGreaterThanEqual:
2879 case glslang::EOpEqual:
2880 case glslang::EOpNotEqual:
2881 case glslang::EOpVectorEqual:
2882 case glslang::EOpVectorNotEqual:
2883 comparison = true;
2884 break;
2885 default:
2886 break;
2887 }
2888
John Kessenich7c1aa102015-10-15 13:29:11 -06002889 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002890 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002891 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002892 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002893 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002894
2895 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002896 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002897 builder.promoteScalar(precision, left, right);
2898
qining25262b32016-05-06 17:25:16 -04002899 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2900 addDecoration(result, noContraction);
2901 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002902 }
2903
2904 if (! comparison)
2905 return 0;
2906
John Kessenich7c1aa102015-10-15 13:29:11 -06002907 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002908
2909 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2910 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2911
John Kessenich22118352015-12-21 20:54:09 -07002912 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002913 }
2914
2915 switch (op) {
2916 case glslang::EOpLessThan:
2917 if (isFloat)
2918 binOp = spv::OpFOrdLessThan;
2919 else if (isUnsigned)
2920 binOp = spv::OpULessThan;
2921 else
2922 binOp = spv::OpSLessThan;
2923 break;
2924 case glslang::EOpGreaterThan:
2925 if (isFloat)
2926 binOp = spv::OpFOrdGreaterThan;
2927 else if (isUnsigned)
2928 binOp = spv::OpUGreaterThan;
2929 else
2930 binOp = spv::OpSGreaterThan;
2931 break;
2932 case glslang::EOpLessThanEqual:
2933 if (isFloat)
2934 binOp = spv::OpFOrdLessThanEqual;
2935 else if (isUnsigned)
2936 binOp = spv::OpULessThanEqual;
2937 else
2938 binOp = spv::OpSLessThanEqual;
2939 break;
2940 case glslang::EOpGreaterThanEqual:
2941 if (isFloat)
2942 binOp = spv::OpFOrdGreaterThanEqual;
2943 else if (isUnsigned)
2944 binOp = spv::OpUGreaterThanEqual;
2945 else
2946 binOp = spv::OpSGreaterThanEqual;
2947 break;
2948 case glslang::EOpEqual:
2949 case glslang::EOpVectorEqual:
2950 if (isFloat)
2951 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002952 else if (isBool)
2953 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 else
2955 binOp = spv::OpIEqual;
2956 break;
2957 case glslang::EOpNotEqual:
2958 case glslang::EOpVectorNotEqual:
2959 if (isFloat)
2960 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002961 else if (isBool)
2962 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 else
2964 binOp = spv::OpINotEqual;
2965 break;
2966 default:
2967 break;
2968 }
2969
qining25262b32016-05-06 17:25:16 -04002970 if (binOp != spv::OpNop) {
2971 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2972 addDecoration(result, noContraction);
2973 return builder.setPrecision(result, precision);
2974 }
John Kessenich140f3df2015-06-26 16:58:36 -06002975
2976 return 0;
2977}
2978
John Kessenich04bb8a02015-12-12 12:28:14 -07002979//
2980// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2981// These can be any of:
2982//
2983// matrix * scalar
2984// scalar * matrix
2985// matrix * matrix linear algebraic
2986// matrix * vector
2987// vector * matrix
2988// matrix * matrix componentwise
2989// matrix op matrix op in {+, -, /}
2990// matrix op scalar op in {+, -, /}
2991// scalar op matrix op in {+, -, /}
2992//
qining25262b32016-05-06 17:25:16 -04002993spv::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 -07002994{
2995 bool firstClass = true;
2996
2997 // First, handle first-class matrix operations (* and matrix/scalar)
2998 switch (op) {
2999 case spv::OpFDiv:
3000 if (builder.isMatrix(left) && builder.isScalar(right)) {
3001 // turn matrix / scalar into a multiply...
3002 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3003 op = spv::OpMatrixTimesScalar;
3004 } else
3005 firstClass = false;
3006 break;
3007 case spv::OpMatrixTimesScalar:
3008 if (builder.isMatrix(right))
3009 std::swap(left, right);
3010 assert(builder.isScalar(right));
3011 break;
3012 case spv::OpVectorTimesMatrix:
3013 assert(builder.isVector(left));
3014 assert(builder.isMatrix(right));
3015 break;
3016 case spv::OpMatrixTimesVector:
3017 assert(builder.isMatrix(left));
3018 assert(builder.isVector(right));
3019 break;
3020 case spv::OpMatrixTimesMatrix:
3021 assert(builder.isMatrix(left));
3022 assert(builder.isMatrix(right));
3023 break;
3024 default:
3025 firstClass = false;
3026 break;
3027 }
3028
qining25262b32016-05-06 17:25:16 -04003029 if (firstClass) {
3030 spv::Id result = builder.createBinOp(op, typeId, left, right);
3031 addDecoration(result, noContraction);
3032 return builder.setPrecision(result, precision);
3033 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003034
LoopDawg592860c2016-06-09 08:57:35 -06003035 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003036 // The result type of all of them is the same type as the (a) matrix operand.
3037 // The algorithm is to:
3038 // - break the matrix(es) into vectors
3039 // - smear any scalar to a vector
3040 // - do vector operations
3041 // - make a matrix out the vector results
3042 switch (op) {
3043 case spv::OpFAdd:
3044 case spv::OpFSub:
3045 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003046 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003047 case spv::OpFMul:
3048 {
3049 // one time set up...
3050 bool leftMat = builder.isMatrix(left);
3051 bool rightMat = builder.isMatrix(right);
3052 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3053 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3054 spv::Id scalarType = builder.getScalarTypeId(typeId);
3055 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3056 std::vector<spv::Id> results;
3057 spv::Id smearVec = spv::NoResult;
3058 if (builder.isScalar(left))
3059 smearVec = builder.smearScalar(precision, left, vecType);
3060 else if (builder.isScalar(right))
3061 smearVec = builder.smearScalar(precision, right, vecType);
3062
3063 // do each vector op
3064 for (unsigned int c = 0; c < numCols; ++c) {
3065 std::vector<unsigned int> indexes;
3066 indexes.push_back(c);
3067 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3068 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003069 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3070 addDecoration(result, noContraction);
3071 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003072 }
3073
3074 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003075 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003076 }
3077 default:
3078 assert(0);
3079 return spv::NoResult;
3080 }
3081}
3082
qining25262b32016-05-06 17:25:16 -04003083spv::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 -06003084{
3085 spv::Op unaryOp = spv::OpNop;
3086 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003087 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003088 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003089
3090 switch (op) {
3091 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003092 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003093 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003094 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003095 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003096 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003097 unaryOp = spv::OpSNegate;
3098 break;
3099
3100 case glslang::EOpLogicalNot:
3101 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003102 unaryOp = spv::OpLogicalNot;
3103 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003104 case glslang::EOpBitwiseNot:
3105 unaryOp = spv::OpNot;
3106 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003107
John Kessenich140f3df2015-06-26 16:58:36 -06003108 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003109 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003110 break;
3111 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003112 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003113 break;
3114 case glslang::EOpTranspose:
3115 unaryOp = spv::OpTranspose;
3116 break;
3117
3118 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003119 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 break;
3124 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003125 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003126 break;
3127 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003128 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
3130 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003131 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003132 break;
3133 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003134 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003135 break;
3136 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003137 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 break;
3139 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003140 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003141 break;
3142
3143 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003145 break;
3146 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003147 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003148 break;
3149 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003150 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003156 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161
3162 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003163 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003164 break;
3165 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003166 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003167 break;
3168
3169 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003170 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003171 break;
3172 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003173 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003174 break;
3175 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003176 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003177 break;
3178 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003179 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003180 break;
3181 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003182 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003183 break;
3184 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003185 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003186 break;
3187
3188 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003189 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003190 break;
3191 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003193 break;
3194 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003195 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003196 break;
3197 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003198 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003202 break;
3203 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003204 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003205 break;
3206
3207 case glslang::EOpIsNan:
3208 unaryOp = spv::OpIsNan;
3209 break;
3210 case glslang::EOpIsInf:
3211 unaryOp = spv::OpIsInf;
3212 break;
LoopDawg592860c2016-06-09 08:57:35 -06003213 case glslang::EOpIsFinite:
3214 unaryOp = spv::OpIsFinite;
3215 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003216
Rex Xucbc426e2015-12-15 16:03:10 +08003217 case glslang::EOpFloatBitsToInt:
3218 case glslang::EOpFloatBitsToUint:
3219 case glslang::EOpIntBitsToFloat:
3220 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003221 case glslang::EOpDoubleBitsToInt64:
3222 case glslang::EOpDoubleBitsToUint64:
3223 case glslang::EOpInt64BitsToDouble:
3224 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003225 unaryOp = spv::OpBitcast;
3226 break;
3227
John Kessenich140f3df2015-06-26 16:58:36 -06003228 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003229 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003230 break;
3231 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003232 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003233 break;
3234 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003235 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003236 break;
3237 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003238 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003239 break;
3240 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003241 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003242 break;
3243 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003244 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003245 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003246 case glslang::EOpPackSnorm4x8:
3247 libCall = spv::GLSLstd450PackSnorm4x8;
3248 break;
3249 case glslang::EOpUnpackSnorm4x8:
3250 libCall = spv::GLSLstd450UnpackSnorm4x8;
3251 break;
3252 case glslang::EOpPackUnorm4x8:
3253 libCall = spv::GLSLstd450PackUnorm4x8;
3254 break;
3255 case glslang::EOpUnpackUnorm4x8:
3256 libCall = spv::GLSLstd450UnpackUnorm4x8;
3257 break;
3258 case glslang::EOpPackDouble2x32:
3259 libCall = spv::GLSLstd450PackDouble2x32;
3260 break;
3261 case glslang::EOpUnpackDouble2x32:
3262 libCall = spv::GLSLstd450UnpackDouble2x32;
3263 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003264
Rex Xu8ff43de2016-04-22 16:51:45 +08003265 case glslang::EOpPackInt2x32:
3266 case glslang::EOpUnpackInt2x32:
3267 case glslang::EOpPackUint2x32:
3268 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003269 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003270 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3271 break;
3272
John Kessenich140f3df2015-06-26 16:58:36 -06003273 case glslang::EOpDPdx:
3274 unaryOp = spv::OpDPdx;
3275 break;
3276 case glslang::EOpDPdy:
3277 unaryOp = spv::OpDPdy;
3278 break;
3279 case glslang::EOpFwidth:
3280 unaryOp = spv::OpFwidth;
3281 break;
3282 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003283 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003284 unaryOp = spv::OpDPdxFine;
3285 break;
3286 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003287 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003288 unaryOp = spv::OpDPdyFine;
3289 break;
3290 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003291 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003292 unaryOp = spv::OpFwidthFine;
3293 break;
3294 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003295 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003296 unaryOp = spv::OpDPdxCoarse;
3297 break;
3298 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003299 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003300 unaryOp = spv::OpDPdyCoarse;
3301 break;
3302 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003303 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003304 unaryOp = spv::OpFwidthCoarse;
3305 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003306 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003307 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003308 libCall = spv::GLSLstd450InterpolateAtCentroid;
3309 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003310 case glslang::EOpAny:
3311 unaryOp = spv::OpAny;
3312 break;
3313 case glslang::EOpAll:
3314 unaryOp = spv::OpAll;
3315 break;
3316
3317 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003318 if (isFloat)
3319 libCall = spv::GLSLstd450FAbs;
3320 else
3321 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003322 break;
3323 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003324 if (isFloat)
3325 libCall = spv::GLSLstd450FSign;
3326 else
3327 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003328 break;
3329
John Kessenichfc51d282015-08-19 13:34:18 -06003330 case glslang::EOpAtomicCounterIncrement:
3331 case glslang::EOpAtomicCounterDecrement:
3332 case glslang::EOpAtomicCounter:
3333 {
3334 // Handle all of the atomics in one place, in createAtomicOperation()
3335 std::vector<spv::Id> operands;
3336 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003337 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003338 }
3339
John Kessenichfc51d282015-08-19 13:34:18 -06003340 case glslang::EOpBitFieldReverse:
3341 unaryOp = spv::OpBitReverse;
3342 break;
3343 case glslang::EOpBitCount:
3344 unaryOp = spv::OpBitCount;
3345 break;
3346 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003347 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003348 break;
3349 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003350 if (isUnsigned)
3351 libCall = spv::GLSLstd450FindUMsb;
3352 else
3353 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003354 break;
3355
Rex Xu574ab042016-04-14 16:53:07 +08003356 case glslang::EOpBallot:
3357 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003358 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003359 libCall = spv::GLSLstd450Bad;
3360 break;
3361
Rex Xu338b1852016-05-05 20:38:33 +08003362 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003363 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003364 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003365 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003366
John Kessenich140f3df2015-06-26 16:58:36 -06003367 default:
3368 return 0;
3369 }
3370
3371 spv::Id id;
3372 if (libCall >= 0) {
3373 std::vector<spv::Id> args;
3374 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003375 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003376 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003377 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003378 }
John Kessenich140f3df2015-06-26 16:58:36 -06003379
qining25262b32016-05-06 17:25:16 -04003380 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003381 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003382}
3383
John Kessenich7a53f762016-01-20 11:19:27 -07003384// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003385spv::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 -07003386{
3387 // Handle unary operations vector by vector.
3388 // The result type is the same type as the original type.
3389 // The algorithm is to:
3390 // - break the matrix into vectors
3391 // - apply the operation to each vector
3392 // - make a matrix out the vector results
3393
3394 // get the types sorted out
3395 int numCols = builder.getNumColumns(operand);
3396 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003397 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3398 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003399 std::vector<spv::Id> results;
3400
3401 // do each vector op
3402 for (int c = 0; c < numCols; ++c) {
3403 std::vector<unsigned int> indexes;
3404 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003405 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3406 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3407 addDecoration(destVec, noContraction);
3408 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003409 }
3410
3411 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003412 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003413}
3414
Rex Xu73e3ce72016-04-27 18:48:17 +08003415spv::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 -06003416{
3417 spv::Op convOp = spv::OpNop;
3418 spv::Id zero = 0;
3419 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003420 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003421
3422 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3423
3424 switch (op) {
3425 case glslang::EOpConvIntToBool:
3426 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003427 case glslang::EOpConvInt64ToBool:
3428 case glslang::EOpConvUint64ToBool:
3429 zero = (op == glslang::EOpConvInt64ToBool ||
3430 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003431 zero = makeSmearedConstant(zero, vectorSize);
3432 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3433
3434 case glslang::EOpConvFloatToBool:
3435 zero = builder.makeFloatConstant(0.0F);
3436 zero = makeSmearedConstant(zero, vectorSize);
3437 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3438
3439 case glslang::EOpConvDoubleToBool:
3440 zero = builder.makeDoubleConstant(0.0);
3441 zero = makeSmearedConstant(zero, vectorSize);
3442 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3443
3444 case glslang::EOpConvBoolToFloat:
3445 convOp = spv::OpSelect;
3446 zero = builder.makeFloatConstant(0.0);
3447 one = builder.makeFloatConstant(1.0);
3448 break;
3449 case glslang::EOpConvBoolToDouble:
3450 convOp = spv::OpSelect;
3451 zero = builder.makeDoubleConstant(0.0);
3452 one = builder.makeDoubleConstant(1.0);
3453 break;
3454 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003455 case glslang::EOpConvBoolToInt64:
3456 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3457 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003458 convOp = spv::OpSelect;
3459 break;
3460 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003461 case glslang::EOpConvBoolToUint64:
3462 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3463 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003464 convOp = spv::OpSelect;
3465 break;
3466
3467 case glslang::EOpConvIntToFloat:
3468 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003469 case glslang::EOpConvInt64ToFloat:
3470 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003471 convOp = spv::OpConvertSToF;
3472 break;
3473
3474 case glslang::EOpConvUintToFloat:
3475 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003476 case glslang::EOpConvUint64ToFloat:
3477 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003478 convOp = spv::OpConvertUToF;
3479 break;
3480
3481 case glslang::EOpConvDoubleToFloat:
3482 case glslang::EOpConvFloatToDouble:
3483 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003484 if (builder.isMatrixType(destType))
3485 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487
3488 case glslang::EOpConvFloatToInt:
3489 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003490 case glslang::EOpConvFloatToInt64:
3491 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003492 convOp = spv::OpConvertFToS;
3493 break;
3494
3495 case glslang::EOpConvUintToInt:
3496 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003497 case glslang::EOpConvUint64ToInt64:
3498 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003499 if (builder.isInSpecConstCodeGenMode()) {
3500 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003501 zero = (op == glslang::EOpConvUintToInt64 ||
3502 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003503 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003504 // Use OpIAdd, instead of OpBitcast to do the conversion when
3505 // generating for OpSpecConstantOp instruction.
3506 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3507 }
3508 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003509 convOp = spv::OpBitcast;
3510 break;
3511
3512 case glslang::EOpConvFloatToUint:
3513 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003514 case glslang::EOpConvFloatToUint64:
3515 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003516 convOp = spv::OpConvertFToU;
3517 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003518
3519 case glslang::EOpConvIntToInt64:
3520 case glslang::EOpConvInt64ToInt:
3521 convOp = spv::OpSConvert;
3522 break;
3523
3524 case glslang::EOpConvUintToUint64:
3525 case glslang::EOpConvUint64ToUint:
3526 convOp = spv::OpUConvert;
3527 break;
3528
3529 case glslang::EOpConvIntToUint64:
3530 case glslang::EOpConvInt64ToUint:
3531 case glslang::EOpConvUint64ToInt:
3532 case glslang::EOpConvUintToInt64:
3533 // OpSConvert/OpUConvert + OpBitCast
3534 switch (op) {
3535 case glslang::EOpConvIntToUint64:
3536 convOp = spv::OpSConvert;
3537 type = builder.makeIntType(64);
3538 break;
3539 case glslang::EOpConvInt64ToUint:
3540 convOp = spv::OpSConvert;
3541 type = builder.makeIntType(32);
3542 break;
3543 case glslang::EOpConvUint64ToInt:
3544 convOp = spv::OpUConvert;
3545 type = builder.makeUintType(32);
3546 break;
3547 case glslang::EOpConvUintToInt64:
3548 convOp = spv::OpUConvert;
3549 type = builder.makeUintType(64);
3550 break;
3551 default:
3552 assert(0);
3553 break;
3554 }
3555
3556 if (vectorSize > 0)
3557 type = builder.makeVectorType(type, vectorSize);
3558
3559 operand = builder.createUnaryOp(convOp, type, operand);
3560
3561 if (builder.isInSpecConstCodeGenMode()) {
3562 // Build zero scalar or vector for OpIAdd.
3563 zero = (op == glslang::EOpConvIntToUint64 ||
3564 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3565 zero = makeSmearedConstant(zero, vectorSize);
3566 // Use OpIAdd, instead of OpBitcast to do the conversion when
3567 // generating for OpSpecConstantOp instruction.
3568 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3569 }
3570 // For normal run-time conversion instruction, use OpBitcast.
3571 convOp = spv::OpBitcast;
3572 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003573 default:
3574 break;
3575 }
3576
3577 spv::Id result = 0;
3578 if (convOp == spv::OpNop)
3579 return result;
3580
3581 if (convOp == spv::OpSelect) {
3582 zero = makeSmearedConstant(zero, vectorSize);
3583 one = makeSmearedConstant(one, vectorSize);
3584 result = builder.createTriOp(convOp, destType, operand, one, zero);
3585 } else
3586 result = builder.createUnaryOp(convOp, destType, operand);
3587
John Kessenich32cfd492016-02-02 12:37:46 -07003588 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003589}
3590
3591spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3592{
3593 if (vectorSize == 0)
3594 return constant;
3595
3596 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3597 std::vector<spv::Id> components;
3598 for (int c = 0; c < vectorSize; ++c)
3599 components.push_back(constant);
3600 return builder.makeCompositeConstant(vectorTypeId, components);
3601}
3602
John Kessenich426394d2015-07-23 10:22:48 -06003603// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003604spv::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 -06003605{
3606 spv::Op opCode = spv::OpNop;
3607
3608 switch (op) {
3609 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003610 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003611 opCode = spv::OpAtomicIAdd;
3612 break;
3613 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003614 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003615 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003616 break;
3617 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003618 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003619 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003620 break;
3621 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003622 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003623 opCode = spv::OpAtomicAnd;
3624 break;
3625 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003626 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003627 opCode = spv::OpAtomicOr;
3628 break;
3629 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003630 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003631 opCode = spv::OpAtomicXor;
3632 break;
3633 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003634 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003635 opCode = spv::OpAtomicExchange;
3636 break;
3637 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003638 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003639 opCode = spv::OpAtomicCompareExchange;
3640 break;
3641 case glslang::EOpAtomicCounterIncrement:
3642 opCode = spv::OpAtomicIIncrement;
3643 break;
3644 case glslang::EOpAtomicCounterDecrement:
3645 opCode = spv::OpAtomicIDecrement;
3646 break;
3647 case glslang::EOpAtomicCounter:
3648 opCode = spv::OpAtomicLoad;
3649 break;
3650 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003651 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003652 break;
3653 }
3654
3655 // Sort out the operands
3656 // - mapping from glslang -> SPV
3657 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003658 // - compare-exchange swaps the value and comparator
3659 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003660 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3661 auto opIt = operands.begin(); // walk the glslang operands
3662 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003663 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3664 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3665 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003666 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3667 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003668 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003669 spvAtomicOperands.push_back(*(opIt + 1));
3670 spvAtomicOperands.push_back(*opIt);
3671 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003672 }
John Kessenich426394d2015-07-23 10:22:48 -06003673
John Kessenich3e60a6f2015-09-14 22:45:16 -06003674 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003675 for (; opIt != operands.end(); ++opIt)
3676 spvAtomicOperands.push_back(*opIt);
3677
3678 return builder.createOp(opCode, typeId, spvAtomicOperands);
3679}
3680
John Kessenich91cef522016-05-05 16:45:40 -06003681// Create group invocation operations.
3682spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3683{
3684 builder.addCapability(spv::CapabilityGroups);
3685
3686 std::vector<spv::Id> operands;
3687 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3688 operands.push_back(operand);
3689
3690 switch (op) {
3691 case glslang::EOpAnyInvocation:
3692 case glslang::EOpAllInvocations:
3693 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3694
3695 case glslang::EOpAllInvocationsEqual:
3696 {
3697 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3698 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3699
3700 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3701 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3702 }
3703 default:
3704 logger->missingFunctionality("invocation operation");
3705 return spv::NoResult;
3706 }
3707}
3708
John Kessenich5e4b1242015-08-06 22:53:06 -06003709spv::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 -06003710{
Rex Xu8ff43de2016-04-22 16:51:45 +08003711 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3713
John Kessenich140f3df2015-06-26 16:58:36 -06003714 spv::Op opCode = spv::OpNop;
3715 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003716 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003717 spv::Id typeId0 = 0;
3718 if (consumedOperands > 0)
3719 typeId0 = builder.getTypeId(operands[0]);
3720 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003721
3722 switch (op) {
3723 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 if (isFloat)
3725 libCall = spv::GLSLstd450FMin;
3726 else if (isUnsigned)
3727 libCall = spv::GLSLstd450UMin;
3728 else
3729 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003730 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003733 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003736 if (isFloat)
3737 libCall = spv::GLSLstd450FMax;
3738 else if (isUnsigned)
3739 libCall = spv::GLSLstd450UMax;
3740 else
3741 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003742 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
3744 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747 case glslang::EOpDot:
3748 opCode = spv::OpDot;
3749 break;
3750 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753
3754 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 if (isFloat)
3756 libCall = spv::GLSLstd450FClamp;
3757 else if (isUnsigned)
3758 libCall = spv::GLSLstd450UClamp;
3759 else
3760 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003761 builder.promoteScalar(precision, operands.front(), operands[1]);
3762 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003763 break;
3764 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003765 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3766 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003767 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003768 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003769 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003770 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003771 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003772 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003773 break;
3774 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003775 libCall = spv::GLSLstd450Step;
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::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003779 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003780 builder.promoteScalar(precision, operands[0], operands[2]);
3781 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003782 break;
3783
3784 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003785 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 break;
3787 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003788 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003789 break;
3790 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003791 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003792 break;
3793 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003794 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003795 break;
3796 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003798 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003799 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003800 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003801 libCall = spv::GLSLstd450InterpolateAtSample;
3802 break;
3803 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003804 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003805 libCall = spv::GLSLstd450InterpolateAtOffset;
3806 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003807 case glslang::EOpAddCarry:
3808 opCode = spv::OpIAddCarry;
3809 typeId = builder.makeStructResultType(typeId0, typeId0);
3810 consumedOperands = 2;
3811 break;
3812 case glslang::EOpSubBorrow:
3813 opCode = spv::OpISubBorrow;
3814 typeId = builder.makeStructResultType(typeId0, typeId0);
3815 consumedOperands = 2;
3816 break;
3817 case glslang::EOpUMulExtended:
3818 opCode = spv::OpUMulExtended;
3819 typeId = builder.makeStructResultType(typeId0, typeId0);
3820 consumedOperands = 2;
3821 break;
3822 case glslang::EOpIMulExtended:
3823 opCode = spv::OpSMulExtended;
3824 typeId = builder.makeStructResultType(typeId0, typeId0);
3825 consumedOperands = 2;
3826 break;
3827 case glslang::EOpBitfieldExtract:
3828 if (isUnsigned)
3829 opCode = spv::OpBitFieldUExtract;
3830 else
3831 opCode = spv::OpBitFieldSExtract;
3832 break;
3833 case glslang::EOpBitfieldInsert:
3834 opCode = spv::OpBitFieldInsert;
3835 break;
3836
3837 case glslang::EOpFma:
3838 libCall = spv::GLSLstd450Fma;
3839 break;
3840 case glslang::EOpFrexp:
3841 libCall = spv::GLSLstd450FrexpStruct;
3842 if (builder.getNumComponents(operands[0]) == 1)
3843 frexpIntType = builder.makeIntegerType(32, true);
3844 else
3845 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3846 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3847 consumedOperands = 1;
3848 break;
3849 case glslang::EOpLdexp:
3850 libCall = spv::GLSLstd450Ldexp;
3851 break;
3852
Rex Xu574ab042016-04-14 16:53:07 +08003853 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003854 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003855 libCall = spv::GLSLstd450Bad;
3856 break;
3857
John Kessenich140f3df2015-06-26 16:58:36 -06003858 default:
3859 return 0;
3860 }
3861
3862 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003863 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003864 // Use an extended instruction from the standard library.
3865 // Construct the call arguments, without modifying the original operands vector.
3866 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3867 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003868 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003869 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003870 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003871 case 0:
3872 // should all be handled by visitAggregate and createNoArgOperation
3873 assert(0);
3874 return 0;
3875 case 1:
3876 // should all be handled by createUnaryOperation
3877 assert(0);
3878 return 0;
3879 case 2:
3880 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3881 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003883 // anything 3 or over doesn't have l-value operands, so all should be consumed
3884 assert(consumedOperands == operands.size());
3885 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003886 break;
3887 }
3888 }
3889
John Kessenich55e7d112015-11-15 21:33:39 -07003890 // Decode the return types that were structures
3891 switch (op) {
3892 case glslang::EOpAddCarry:
3893 case glslang::EOpSubBorrow:
3894 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3895 id = builder.createCompositeExtract(id, typeId0, 0);
3896 break;
3897 case glslang::EOpUMulExtended:
3898 case glslang::EOpIMulExtended:
3899 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3900 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3901 break;
3902 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003903 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003904 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3905 id = builder.createCompositeExtract(id, typeId0, 0);
3906 break;
3907 default:
3908 break;
3909 }
3910
John Kessenich32cfd492016-02-02 12:37:46 -07003911 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003912}
3913
3914// Intrinsics with no arguments, no return value, and no precision.
3915spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3916{
3917 // TODO: get the barrier operands correct
3918
3919 switch (op) {
3920 case glslang::EOpEmitVertex:
3921 builder.createNoResultOp(spv::OpEmitVertex);
3922 return 0;
3923 case glslang::EOpEndPrimitive:
3924 builder.createNoResultOp(spv::OpEndPrimitive);
3925 return 0;
3926 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003927 if (glslangIntermediate->getProfile() != EEsProfile)
3928 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003929 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003930 return 0;
3931 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003932 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003933 return 0;
3934 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003935 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003936 return 0;
3937 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003938 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003939 return 0;
3940 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003941 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003942 return 0;
3943 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003944 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003945 return 0;
3946 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003947 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003948 return 0;
3949 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003950 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003951 return 0;
3952 }
3953}
3954
3955spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3956{
John Kessenich2f273362015-07-18 22:34:27 -06003957 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003958 spv::Id id;
3959 if (symbolValues.end() != iter) {
3960 id = iter->second;
3961 return id;
3962 }
3963
3964 // it was not found, create it
3965 id = createSpvVariable(symbol);
3966 symbolValues[symbol->getId()] = id;
3967
3968 if (! symbol->getType().isStruct()) {
3969 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003970 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003971 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003972 if (symbol->getType().getQualifier().hasSpecConstantId())
3973 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003974 if (symbol->getQualifier().hasIndex())
3975 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3976 if (symbol->getQualifier().hasComponent())
3977 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3978 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003979 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003980 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003981 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003982 if (symbol->getQualifier().hasXfbBuffer())
3983 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3984 if (symbol->getQualifier().hasXfbOffset())
3985 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3986 }
3987 }
3988
scygan2c864272016-05-18 18:09:17 +02003989 if (symbol->getQualifier().hasLocation())
3990 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003991 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003992 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003993 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003994 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003995 }
John Kessenich140f3df2015-06-26 16:58:36 -06003996 if (symbol->getQualifier().hasSet())
3997 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003998 else if (IsDescriptorResource(symbol->getType())) {
3999 // default to 0
4000 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4001 }
John Kessenich140f3df2015-06-26 16:58:36 -06004002 if (symbol->getQualifier().hasBinding())
4003 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004004 if (symbol->getQualifier().hasAttachment())
4005 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004006 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004007 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004008 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004009 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004010 if (symbol->getQualifier().hasXfbBuffer())
4011 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4012 }
4013
Rex Xu1da878f2016-02-21 20:59:01 +08004014 if (symbol->getType().isImage()) {
4015 std::vector<spv::Decoration> memory;
4016 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4017 for (unsigned int i = 0; i < memory.size(); ++i)
4018 addDecoration(id, memory[i]);
4019 }
4020
John Kessenich140f3df2015-06-26 16:58:36 -06004021 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004022 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004023 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004024 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004025
John Kessenich140f3df2015-06-26 16:58:36 -06004026 return id;
4027}
4028
John Kessenich55e7d112015-11-15 21:33:39 -07004029// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004030void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4031{
4032 if (dec != spv::BadValue)
4033 builder.addDecoration(id, dec);
4034}
4035
John Kessenich55e7d112015-11-15 21:33:39 -07004036// If 'dec' is valid, add a one-operand decoration to an object
4037void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4038{
4039 if (dec != spv::BadValue)
4040 builder.addDecoration(id, dec, value);
4041}
4042
4043// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004044void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4045{
4046 if (dec != spv::BadValue)
4047 builder.addMemberDecoration(id, (unsigned)member, dec);
4048}
4049
John Kessenich92187592016-02-01 13:45:25 -07004050// If 'dec' is valid, add a one-operand decoration to a struct member
4051void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4052{
4053 if (dec != spv::BadValue)
4054 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4055}
4056
John Kessenich55e7d112015-11-15 21:33:39 -07004057// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004058// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004059//
4060// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4061//
4062// Recursively walk the nodes. The nodes form a tree whose leaves are
4063// regular constants, which themselves are trees that createSpvConstant()
4064// recursively walks. So, this function walks the "top" of the tree:
4065// - emit specialization constant-building instructions for specConstant
4066// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004067spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004068{
John Kessenich7cc0e282016-03-20 00:46:02 -06004069 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004070
qining4f4bb812016-04-03 23:55:17 -04004071 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004072 if (! node.getQualifier().specConstant) {
4073 // hand off to the non-spec-constant path
4074 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4075 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004076 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004077 nextConst, false);
4078 }
4079
4080 // We now know we have a specialization constant to build
4081
John Kessenichd94c0032016-05-30 19:29:40 -06004082 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004083 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4084 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4085 std::vector<spv::Id> dimConstId;
4086 for (int dim = 0; dim < 3; ++dim) {
4087 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4088 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4089 if (specConst)
4090 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4091 }
4092 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4093 }
4094
4095 // An AST node labelled as specialization constant should be a symbol node.
4096 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4097 if (auto* sn = node.getAsSymbolNode()) {
4098 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004099 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4100 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4101 // will set the builder into spec constant op instruction generating mode.
4102 sub_tree->traverse(this);
4103 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004104 } else if (auto* const_union_array = &sn->getConstArray()){
4105 int nextConst = 0;
4106 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004107 }
4108 }
qining4f4bb812016-04-03 23:55:17 -04004109
4110 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4111 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004112 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004113 exit(1);
4114 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004115}
4116
John Kessenich140f3df2015-06-26 16:58:36 -06004117// Use 'consts' as the flattened glslang source of scalar constants to recursively
4118// build the aggregate SPIR-V constant.
4119//
4120// If there are not enough elements present in 'consts', 0 will be substituted;
4121// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4122//
qining08408382016-03-21 09:51:37 -04004123spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004124{
4125 // vector of constants for SPIR-V
4126 std::vector<spv::Id> spvConsts;
4127
4128 // Type is used for struct and array constants
4129 spv::Id typeId = convertGlslangToSpvType(glslangType);
4130
4131 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004132 glslang::TType elementType(glslangType, 0);
4133 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004134 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004135 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004136 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004137 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004138 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004139 } else if (glslangType.getStruct()) {
4140 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4141 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004142 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004143 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004144 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4145 bool zero = nextConst >= consts.size();
4146 switch (glslangType.getBasicType()) {
4147 case glslang::EbtInt:
4148 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4149 break;
4150 case glslang::EbtUint:
4151 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4152 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004153 case glslang::EbtInt64:
4154 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4155 break;
4156 case glslang::EbtUint64:
4157 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4158 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004159 case glslang::EbtFloat:
4160 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4161 break;
4162 case glslang::EbtDouble:
4163 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4164 break;
4165 case glslang::EbtBool:
4166 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4167 break;
4168 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004169 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004170 break;
4171 }
4172 ++nextConst;
4173 }
4174 } else {
4175 // we have a non-aggregate (scalar) constant
4176 bool zero = nextConst >= consts.size();
4177 spv::Id scalar = 0;
4178 switch (glslangType.getBasicType()) {
4179 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004180 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004181 break;
4182 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004183 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004184 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004185 case glslang::EbtInt64:
4186 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4187 break;
4188 case glslang::EbtUint64:
4189 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4190 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004191 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004192 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004193 break;
4194 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004195 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004196 break;
4197 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004198 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004199 break;
4200 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004201 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004202 break;
4203 }
4204 ++nextConst;
4205 return scalar;
4206 }
4207
4208 return builder.makeCompositeConstant(typeId, spvConsts);
4209}
4210
John Kessenich7c1aa102015-10-15 13:29:11 -06004211// Return true if the node is a constant or symbol whose reading has no
4212// non-trivial observable cost or effect.
4213bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4214{
4215 // don't know what this is
4216 if (node == nullptr)
4217 return false;
4218
4219 // a constant is safe
4220 if (node->getAsConstantUnion() != nullptr)
4221 return true;
4222
4223 // not a symbol means non-trivial
4224 if (node->getAsSymbolNode() == nullptr)
4225 return false;
4226
4227 // a symbol, depends on what's being read
4228 switch (node->getType().getQualifier().storage) {
4229 case glslang::EvqTemporary:
4230 case glslang::EvqGlobal:
4231 case glslang::EvqIn:
4232 case glslang::EvqInOut:
4233 case glslang::EvqConst:
4234 case glslang::EvqConstReadOnly:
4235 case glslang::EvqUniform:
4236 return true;
4237 default:
4238 return false;
4239 }
qining25262b32016-05-06 17:25:16 -04004240}
John Kessenich7c1aa102015-10-15 13:29:11 -06004241
4242// A node is trivial if it is a single operation with no side effects.
4243// Error on the side of saying non-trivial.
4244// Return true if trivial.
4245bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4246{
4247 if (node == nullptr)
4248 return false;
4249
4250 // symbols and constants are trivial
4251 if (isTrivialLeaf(node))
4252 return true;
4253
4254 // otherwise, it needs to be a simple operation or one or two leaf nodes
4255
4256 // not a simple operation
4257 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4258 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4259 if (binaryNode == nullptr && unaryNode == nullptr)
4260 return false;
4261
4262 // not on leaf nodes
4263 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4264 return false;
4265
4266 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4267 return false;
4268 }
4269
4270 switch (node->getAsOperator()->getOp()) {
4271 case glslang::EOpLogicalNot:
4272 case glslang::EOpConvIntToBool:
4273 case glslang::EOpConvUintToBool:
4274 case glslang::EOpConvFloatToBool:
4275 case glslang::EOpConvDoubleToBool:
4276 case glslang::EOpEqual:
4277 case glslang::EOpNotEqual:
4278 case glslang::EOpLessThan:
4279 case glslang::EOpGreaterThan:
4280 case glslang::EOpLessThanEqual:
4281 case glslang::EOpGreaterThanEqual:
4282 case glslang::EOpIndexDirect:
4283 case glslang::EOpIndexDirectStruct:
4284 case glslang::EOpLogicalXor:
4285 case glslang::EOpAny:
4286 case glslang::EOpAll:
4287 return true;
4288 default:
4289 return false;
4290 }
4291}
4292
4293// Emit short-circuiting code, where 'right' is never evaluated unless
4294// the left side is true (for &&) or false (for ||).
4295spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4296{
4297 spv::Id boolTypeId = builder.makeBoolType();
4298
4299 // emit left operand
4300 builder.clearAccessChain();
4301 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004302 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004303
4304 // Operands to accumulate OpPhi operands
4305 std::vector<spv::Id> phiOperands;
4306 // accumulate left operand's phi information
4307 phiOperands.push_back(leftId);
4308 phiOperands.push_back(builder.getBuildPoint()->getId());
4309
4310 // Make the two kinds of operation symmetric with a "!"
4311 // || => emit "if (! left) result = right"
4312 // && => emit "if ( left) result = right"
4313 //
4314 // TODO: this runtime "not" for || could be avoided by adding functionality
4315 // to 'builder' to have an "else" without an "then"
4316 if (op == glslang::EOpLogicalOr)
4317 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4318
4319 // make an "if" based on the left value
4320 spv::Builder::If ifBuilder(leftId, builder);
4321
4322 // emit right operand as the "then" part of the "if"
4323 builder.clearAccessChain();
4324 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004325 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004326
4327 // accumulate left operand's phi information
4328 phiOperands.push_back(rightId);
4329 phiOperands.push_back(builder.getBuildPoint()->getId());
4330
4331 // finish the "if"
4332 ifBuilder.makeEndIf();
4333
4334 // phi together the two results
4335 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4336}
4337
John Kessenich140f3df2015-06-26 16:58:36 -06004338}; // end anonymous namespace
4339
4340namespace glslang {
4341
John Kessenich68d78fd2015-07-12 19:28:10 -06004342void GetSpirvVersion(std::string& version)
4343{
John Kessenich9e55f632015-07-15 10:03:39 -06004344 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004345 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004346 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004347 version = buf;
4348}
4349
John Kessenich140f3df2015-06-26 16:58:36 -06004350// Write SPIR-V out to a binary file
4351void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4352{
4353 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004354 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004355 for (int i = 0; i < (int)spirv.size(); ++i) {
4356 unsigned int word = spirv[i];
4357 out.write((const char*)&word, 4);
4358 }
4359 out.close();
4360}
4361
4362//
4363// Set up the glslang traversal
4364//
4365void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4366{
Lei Zhang17535f72016-05-04 15:55:59 -04004367 spv::SpvBuildLogger logger;
4368 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004369}
4370
Lei Zhang17535f72016-05-04 15:55:59 -04004371void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004372{
John Kessenich140f3df2015-06-26 16:58:36 -06004373 TIntermNode* root = intermediate.getTreeRoot();
4374
4375 if (root == 0)
4376 return;
4377
4378 glslang::GetThreadPoolAllocator().push();
4379
Lei Zhang17535f72016-05-04 15:55:59 -04004380 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004381
4382 root->traverse(&it);
4383
4384 it.dumpSpv(spirv);
4385
4386 glslang::GetThreadPoolAllocator().pop();
4387}
4388
4389}; // end namespace glslang