blob: d9d3555e8ada4b4730a78dc7a0449b0f0db2a59a [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//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:
John Kessenich5e801132016-02-15 11:09:46 -0700111 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenichebb50532016-05-16 19:22:05 -0600112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool member);
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);
John Kessenichebb50532016-05-16 19:22:05 -0600125 void declareClipCullCapability(const glslang::TTypeList& members, int member);
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;
230 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700231 if (type.getQualifier().layoutPushConstant)
232 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 if (type.getBasicType() == glslang::EbtBlock)
234 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800235 else if (type.getBasicType() == glslang::EbtAtomicUint)
236 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 else
238 return spv::StorageClassUniformConstant;
239 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
240 } else {
241 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700242 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
243 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600244 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
245 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400246 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700247 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600248 return spv::StorageClassFunction;
249 }
250 }
251}
252
253// Translate glslang sampler type to SPIR-V dimensionality.
254spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
255{
256 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700257 case glslang::Esd1D: return spv::Dim1D;
258 case glslang::Esd2D: return spv::Dim2D;
259 case glslang::Esd3D: return spv::Dim3D;
260 case glslang::EsdCube: return spv::DimCube;
261 case glslang::EsdRect: return spv::DimRect;
262 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700263 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700265 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::Dim2D;
267 }
268}
269
270// Translate glslang type to SPIR-V precision decorations.
271spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
272{
273 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700274 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600275 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600276 default:
277 return spv::NoPrecision;
278 }
279}
280
281// Translate glslang type to SPIR-V block decorations.
282spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
283{
284 if (type.getBasicType() == glslang::EbtBlock) {
285 switch (type.getQualifier().storage) {
286 case glslang::EvqUniform: return spv::DecorationBlock;
287 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
288 case glslang::EvqVaryingIn: return spv::DecorationBlock;
289 case glslang::EvqVaryingOut: return spv::DecorationBlock;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 break;
293 }
294 }
295
296 return (spv::Decoration)spv::BadValue;
297}
298
Rex Xu1da878f2016-02-21 20:59:01 +0800299// Translate glslang type to SPIR-V memory decorations.
300void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
301{
302 if (qualifier.coherent)
303 memory.push_back(spv::DecorationCoherent);
304 if (qualifier.volatil)
305 memory.push_back(spv::DecorationVolatile);
306 if (qualifier.restrict)
307 memory.push_back(spv::DecorationRestrict);
308 if (qualifier.readonly)
309 memory.push_back(spv::DecorationNonWritable);
310 if (qualifier.writeonly)
311 memory.push_back(spv::DecorationNonReadable);
312}
313
John Kessenich140f3df2015-06-26 16:58:36 -0600314// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700315spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600316{
317 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700318 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600319 case glslang::ElmRowMajor:
320 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 default:
324 // opaque layouts don't need a majorness
325 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 }
327 } else {
328 switch (type.getBasicType()) {
329 default:
330 return (spv::Decoration)spv::BadValue;
331 break;
332 case glslang::EbtBlock:
333 switch (type.getQualifier().storage) {
334 case glslang::EvqUniform:
335 case glslang::EvqBuffer:
336 switch (type.getQualifier().layoutPacking) {
337 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
339 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600340 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 }
342 case glslang::EvqVaryingIn:
343 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700344 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return (spv::Decoration)spv::BadValue;
349 }
350 }
351 }
352}
353
354// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700355// Returns spv::Decoration(spv::BadValue) when no decoration
356// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700357spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600358{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700359 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700360 // Smooth decoration doesn't exist in SPIR-V 1.0
361 return (spv::Decoration)spv::BadValue;
362 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700363 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700365 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600366 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700369 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600370 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700371 else if (qualifier.sample) {
372 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600373 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700374 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600375 return (spv::Decoration)spv::BadValue;
376}
377
John Kessenich92187592016-02-01 13:45:25 -0700378// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600380{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700381 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600382 return spv::DecorationInvariant;
383 else
384 return (spv::Decoration)spv::BadValue;
385}
386
qining9220dbb2016-05-04 17:34:38 -0400387// If glslang type is noContraction, return SPIR-V NoContraction decoration.
388spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
389{
390 if (qualifier.noContraction)
391 return spv::DecorationNoContraction;
392 else
393 return (spv::Decoration)spv::BadValue;
394}
395
John Kessenich140f3df2015-06-26 16:58:36 -0600396// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenichebb50532016-05-16 19:22:05 -0600397spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool member)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
399 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700400 case glslang::EbvPointSize:
401 switch (glslangIntermediate->getStage()) {
402 case EShLangGeometry:
403 builder.addCapability(spv::CapabilityGeometryPointSize);
404 break;
405 case EShLangTessControl:
406 case EShLangTessEvaluation:
407 builder.addCapability(spv::CapabilityTessellationPointSize);
408 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100409 default:
410 break;
John Kessenich92187592016-02-01 13:45:25 -0700411 }
412 return spv::BuiltInPointSize;
413
John Kessenichebb50532016-05-16 19:22:05 -0600414 // These *Distance capabilities logically belong here, but if the member is declared and
415 // then never used, consumers of SPIR-V prefer the capability not be declared.
416 // They are now generated when used, rather than here when declared.
417 // Potentially, the specification should be more clear what the minimum
418 // use needed is to trigger the capability.
419 //
John Kessenich92187592016-02-01 13:45:25 -0700420 case glslang::EbvClipDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600421 if (! member)
422 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700423 return spv::BuiltInClipDistance;
424
425 case glslang::EbvCullDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600426 if (! member)
427 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700428 return spv::BuiltInCullDistance;
429
430 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500431 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700432 return spv::BuiltInViewportIndex;
433
John Kessenich5e801132016-02-15 11:09:46 -0700434 case glslang::EbvSampleId:
435 builder.addCapability(spv::CapabilitySampleRateShading);
436 return spv::BuiltInSampleId;
437
438 case glslang::EbvSamplePosition:
439 builder.addCapability(spv::CapabilitySampleRateShading);
440 return spv::BuiltInSamplePosition;
441
442 case glslang::EbvSampleMask:
443 builder.addCapability(spv::CapabilitySampleRateShading);
444 return spv::BuiltInSampleMask;
445
John Kessenich140f3df2015-06-26 16:58:36 -0600446 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600447 case glslang::EbvVertexId: return spv::BuiltInVertexId;
448 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700449 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
450 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600451 case glslang::EbvBaseVertex:
452 case glslang::EbvBaseInstance:
453 case glslang::EbvDrawId:
454 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600455 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600456 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600457 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
458 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
459 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600460 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
461 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
462 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
463 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
464 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
465 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
466 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600467 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
468 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
469 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
470 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
471 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
472 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
473 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
474 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800475 case glslang::EbvSubGroupSize:
476 case glslang::EbvSubGroupInvocation:
477 case glslang::EbvSubGroupEqMask:
478 case glslang::EbvSubGroupGeMask:
479 case glslang::EbvSubGroupGtMask:
480 case glslang::EbvSubGroupLeMask:
481 case glslang::EbvSubGroupLtMask:
482 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600483 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800484 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600485 default: return (spv::BuiltIn)spv::BadValue;
486 }
487}
488
Rex Xufc618912015-09-09 16:42:49 +0800489// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700490spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800491{
492 assert(type.getBasicType() == glslang::EbtSampler);
493
John Kessenich5d0fa972016-02-15 11:57:00 -0700494 // Check for capabilities
495 switch (type.getQualifier().layoutFormat) {
496 case glslang::ElfRg32f:
497 case glslang::ElfRg16f:
498 case glslang::ElfR11fG11fB10f:
499 case glslang::ElfR16f:
500 case glslang::ElfRgba16:
501 case glslang::ElfRgb10A2:
502 case glslang::ElfRg16:
503 case glslang::ElfRg8:
504 case glslang::ElfR16:
505 case glslang::ElfR8:
506 case glslang::ElfRgba16Snorm:
507 case glslang::ElfRg16Snorm:
508 case glslang::ElfRg8Snorm:
509 case glslang::ElfR16Snorm:
510 case glslang::ElfR8Snorm:
511
512 case glslang::ElfRg32i:
513 case glslang::ElfRg16i:
514 case glslang::ElfRg8i:
515 case glslang::ElfR16i:
516 case glslang::ElfR8i:
517
518 case glslang::ElfRgb10a2ui:
519 case glslang::ElfRg32ui:
520 case glslang::ElfRg16ui:
521 case glslang::ElfRg8ui:
522 case glslang::ElfR16ui:
523 case glslang::ElfR8ui:
524 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
525 break;
526
527 default:
528 break;
529 }
530
531 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800532 switch (type.getQualifier().layoutFormat) {
533 case glslang::ElfNone: return spv::ImageFormatUnknown;
534 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
535 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
536 case glslang::ElfR32f: return spv::ImageFormatR32f;
537 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
538 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
539 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
540 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
541 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
542 case glslang::ElfR16f: return spv::ImageFormatR16f;
543 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
544 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
545 case glslang::ElfRg16: return spv::ImageFormatRg16;
546 case glslang::ElfRg8: return spv::ImageFormatRg8;
547 case glslang::ElfR16: return spv::ImageFormatR16;
548 case glslang::ElfR8: return spv::ImageFormatR8;
549 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
550 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
551 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
552 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
553 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
554 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
555 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
556 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
557 case glslang::ElfR32i: return spv::ImageFormatR32i;
558 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
559 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
560 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
561 case glslang::ElfR16i: return spv::ImageFormatR16i;
562 case glslang::ElfR8i: return spv::ImageFormatR8i;
563 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
564 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
565 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
566 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
567 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
568 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
569 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
570 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
571 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
572 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
573 default: return (spv::ImageFormat)spv::BadValue;
574 }
575}
576
qining25262b32016-05-06 17:25:16 -0400577// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700578// descriptor set.
579bool IsDescriptorResource(const glslang::TType& type)
580{
John Kessenichf7497e22016-03-08 21:36:22 -0700581 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700582 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700583 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700584
585 // non block...
586 // basically samplerXXX/subpass/sampler/texture are all included
587 // if they are the global-scope-class, not the function parameter
588 // (or local, if they ever exist) class.
589 if (type.getBasicType() == glslang::EbtSampler)
590 return type.getQualifier().isUniformOrBuffer();
591
592 // None of the above.
593 return false;
594}
595
John Kesseniche0b6cad2015-12-24 10:30:13 -0700596void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
597{
598 if (child.layoutMatrix == glslang::ElmNone)
599 child.layoutMatrix = parent.layoutMatrix;
600
601 if (parent.invariant)
602 child.invariant = true;
603 if (parent.nopersp)
604 child.nopersp = true;
605 if (parent.flat)
606 child.flat = true;
607 if (parent.centroid)
608 child.centroid = true;
609 if (parent.patch)
610 child.patch = true;
611 if (parent.sample)
612 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800613 if (parent.coherent)
614 child.coherent = true;
615 if (parent.volatil)
616 child.volatil = true;
617 if (parent.restrict)
618 child.restrict = true;
619 if (parent.readonly)
620 child.readonly = true;
621 if (parent.writeonly)
622 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700623}
624
625bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
626{
John Kessenich7b9fa252016-01-21 18:56:57 -0700627 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700628 // - struct members can inherit from a struct declaration
629 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
630 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400631 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700632}
633
John Kessenich140f3df2015-06-26 16:58:36 -0600634//
635// Implement the TGlslangToSpvTraverser class.
636//
637
Lei Zhang17535f72016-05-04 15:55:59 -0400638TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
639 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
640 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600641 inMain(false), mainTerminated(false), linkageOnly(false),
642 glslangIntermediate(glslangIntermediate)
643{
644 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
645
646 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700647 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600648 stdBuiltins = builder.import("GLSL.std.450");
649 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700650 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
651 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600652
653 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600654 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
655 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600656 builder.addSourceExtension(it->c_str());
657
658 // Add the top-level modes for this shader.
659
John Kessenich92187592016-02-01 13:45:25 -0700660 if (glslangIntermediate->getXfbMode()) {
661 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600662 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700663 }
John Kessenich140f3df2015-06-26 16:58:36 -0600664
665 unsigned int mode;
666 switch (glslangIntermediate->getStage()) {
667 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600668 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600669 break;
670
671 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600672 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600673 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
674 break;
675
676 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600677 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600678 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700679 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
680 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
681 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600682 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600683 }
684 if (mode != spv::BadValue)
685 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
686
John Kesseniche6903322015-10-13 16:29:02 -0600687 switch (glslangIntermediate->getVertexSpacing()) {
688 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
689 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
690 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
691 default: mode = spv::BadValue; break;
692 }
693 if (mode != spv::BadValue)
694 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
695
696 switch (glslangIntermediate->getVertexOrder()) {
697 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
698 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
699 default: mode = spv::BadValue; break;
700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703
704 if (glslangIntermediate->getPointMode())
705 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600706 break;
707
708 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600709 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600710 switch (glslangIntermediate->getInputPrimitive()) {
711 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
712 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
713 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700714 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600715 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
716 default: mode = spv::BadValue; break;
717 }
718 if (mode != spv::BadValue)
719 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600720
John Kessenich140f3df2015-06-26 16:58:36 -0600721 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
722
723 switch (glslangIntermediate->getOutputPrimitive()) {
724 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
725 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
726 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
727 default: mode = spv::BadValue; break;
728 }
729 if (mode != spv::BadValue)
730 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
732 break;
733
734 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600735 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600736 if (glslangIntermediate->getPixelCenterInteger())
737 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600738
John Kessenich140f3df2015-06-26 16:58:36 -0600739 if (glslangIntermediate->getOriginUpperLeft())
740 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600741 else
742 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600743
744 if (glslangIntermediate->getEarlyFragmentTests())
745 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
746
747 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600748 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
749 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
750 default: mode = spv::BadValue; break;
751 }
752 if (mode != spv::BadValue)
753 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
754
755 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
756 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600757 break;
758
759 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600760 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600761 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
762 glslangIntermediate->getLocalSize(1),
763 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600764 break;
765
766 default:
767 break;
768 }
769
770}
771
John Kessenich7ba63412015-12-20 17:37:07 -0700772// Finish everything and dump
773void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
774{
775 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100776 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
777 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700778
qiningda397332016-03-09 19:54:03 -0500779 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700780 builder.dump(out);
781}
782
John Kessenich140f3df2015-06-26 16:58:36 -0600783TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
784{
785 if (! mainTerminated) {
786 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
787 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600788 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600789 }
790}
791
792//
793// Implement the traversal functions.
794//
795// Return true from interior nodes to have the external traversal
796// continue on to children. Return false if children were
797// already processed.
798//
799
800//
qining25262b32016-05-06 17:25:16 -0400801// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600802// - uniform/input reads
803// - output writes
804// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
805// - something simple that degenerates into the last bullet
806//
807void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
808{
qining75d1d802016-04-06 14:42:01 -0400809 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
810 if (symbol->getType().getQualifier().isSpecConstant())
811 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
812
John Kessenich140f3df2015-06-26 16:58:36 -0600813 // getSymbolId() will set up all the IO decorations on the first call.
814 // Formal function parameters were mapped during makeFunctions().
815 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700816
817 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
818 if (builder.isPointer(id)) {
819 spv::StorageClass sc = builder.getStorageClass(id);
820 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
821 iOSet.insert(id);
822 }
823
824 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700825 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600826 // Prepare to generate code for the access
827
828 // L-value chains will be computed left to right. We're on the symbol now,
829 // which is the left-most part of the access chain, so now is "clear" time,
830 // followed by setting the base.
831 builder.clearAccessChain();
832
833 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700834 // except for
835 // A) "const in" arguments to a function, which are an intermediate object.
836 // See comments in handleUserFunctionCall().
837 // B) Specialization constants (normal constant don't even come in as a variable),
838 // These are also pure R-values.
839 glslang::TQualifier qualifier = symbol->getQualifier();
840 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
841 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600842 builder.setAccessChainRValue(id);
843 else
844 builder.setAccessChainLValue(id);
845 }
846}
847
848bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
849{
qining40887662016-04-03 22:20:42 -0400850 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
851 if (node->getType().getQualifier().isSpecConstant())
852 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
853
John Kessenich140f3df2015-06-26 16:58:36 -0600854 // First, handle special cases
855 switch (node->getOp()) {
856 case glslang::EOpAssign:
857 case glslang::EOpAddAssign:
858 case glslang::EOpSubAssign:
859 case glslang::EOpMulAssign:
860 case glslang::EOpVectorTimesMatrixAssign:
861 case glslang::EOpVectorTimesScalarAssign:
862 case glslang::EOpMatrixTimesScalarAssign:
863 case glslang::EOpMatrixTimesMatrixAssign:
864 case glslang::EOpDivAssign:
865 case glslang::EOpModAssign:
866 case glslang::EOpAndAssign:
867 case glslang::EOpInclusiveOrAssign:
868 case glslang::EOpExclusiveOrAssign:
869 case glslang::EOpLeftShiftAssign:
870 case glslang::EOpRightShiftAssign:
871 // A bin-op assign "a += b" means the same thing as "a = a + b"
872 // where a is evaluated before b. For a simple assignment, GLSL
873 // says to evaluate the left before the right. So, always, left
874 // node then right node.
875 {
876 // get the left l-value, save it away
877 builder.clearAccessChain();
878 node->getLeft()->traverse(this);
879 spv::Builder::AccessChain lValue = builder.getAccessChain();
880
881 // evaluate the right
882 builder.clearAccessChain();
883 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700884 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600885
886 if (node->getOp() != glslang::EOpAssign) {
887 // the left is also an r-value
888 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700889 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600890
891 // do the operation
qining25262b32016-05-06 17:25:16 -0400892 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
893 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600894 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
895 node->getType().getBasicType());
896
897 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700898 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600899 }
900
901 // store the result
902 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800903 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600904
905 // assignments are expressions having an rValue after they are evaluated...
906 builder.clearAccessChain();
907 builder.setAccessChainRValue(rValue);
908 }
909 return false;
910 case glslang::EOpIndexDirect:
911 case glslang::EOpIndexDirectStruct:
912 {
913 // Get the left part of the access chain.
914 node->getLeft()->traverse(this);
915
916 // Add the next element in the chain
917
John Kessenich55e7d112015-11-15 21:33:39 -0700918 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600919 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
920 // This may be, e.g., an anonymous block-member selection, which generally need
921 // index remapping due to hidden members in anonymous blocks.
922 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700923 assert(remapper.size() > 0);
924 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600925 }
926
927 if (! node->getLeft()->getType().isArray() &&
928 node->getLeft()->getType().isVector() &&
929 node->getOp() == glslang::EOpIndexDirect) {
930 // This is essentially a hard-coded vector swizzle of size 1,
931 // so short circuit the access-chain stuff with a swizzle.
932 std::vector<unsigned> swizzle;
933 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600934 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600935 } else {
936 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600937 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenichebb50532016-05-16 19:22:05 -0600938
939 // Add capabilities here for accessing clip/cull distance
940 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
941 declareClipCullCapability(*node->getLeft()->getType().getStruct(), index);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 }
943 }
944 return false;
945 case glslang::EOpIndexIndirect:
946 {
947 // Structure or array or vector indirection.
948 // Will use native SPIR-V access-chain for struct and array indirection;
949 // matrices are arrays of vectors, so will also work for a matrix.
950 // Will use the access chain's 'component' for variable index into a vector.
951
952 // This adapter is building access chains left to right.
953 // Set up the access chain to the left.
954 node->getLeft()->traverse(this);
955
956 // save it so that computing the right side doesn't trash it
957 spv::Builder::AccessChain partial = builder.getAccessChain();
958
959 // compute the next index in the chain
960 builder.clearAccessChain();
961 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700962 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600963
964 // restore the saved access chain
965 builder.setAccessChain(partial);
966
967 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600968 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600969 else
John Kessenichfa668da2015-09-13 14:46:30 -0600970 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600971 }
972 return false;
973 case glslang::EOpVectorSwizzle:
974 {
975 node->getLeft()->traverse(this);
976 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
977 std::vector<unsigned> swizzle;
978 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
979 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600980 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600981 }
982 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600983 case glslang::EOpLogicalOr:
984 case glslang::EOpLogicalAnd:
985 {
986
987 // These may require short circuiting, but can sometimes be done as straight
988 // binary operations. The right operand must be short circuited if it has
989 // side effects, and should probably be if it is complex.
990 if (isTrivial(node->getRight()->getAsTyped()))
991 break; // handle below as a normal binary operation
992 // otherwise, we need to do dynamic short circuiting on the right operand
993 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
994 builder.clearAccessChain();
995 builder.setAccessChainRValue(result);
996 }
997 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600998 default:
999 break;
1000 }
1001
1002 // Assume generic binary op...
1003
John Kessenich32cfd492016-02-02 12:37:46 -07001004 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001005 builder.clearAccessChain();
1006 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001007 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001008
John Kessenich32cfd492016-02-02 12:37:46 -07001009 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001010 builder.clearAccessChain();
1011 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001012 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001013
John Kessenich32cfd492016-02-02 12:37:46 -07001014 // get result
1015 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001016 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001017 convertGlslangToSpvType(node->getType()), left, right,
1018 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001019
John Kessenich50e57562015-12-21 21:21:11 -07001020 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001021 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001022 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001023 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001024 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001025 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001026 return false;
1027 }
John Kessenich140f3df2015-06-26 16:58:36 -06001028}
1029
1030bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1031{
qining40887662016-04-03 22:20:42 -04001032 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1033 if (node->getType().getQualifier().isSpecConstant())
1034 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1035
John Kessenichfc51d282015-08-19 13:34:18 -06001036 spv::Id result = spv::NoResult;
1037
1038 // try texturing first
1039 result = createImageTextureFunctionCall(node);
1040 if (result != spv::NoResult) {
1041 builder.clearAccessChain();
1042 builder.setAccessChainRValue(result);
1043
1044 return false; // done with this node
1045 }
1046
1047 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001048
1049 if (node->getOp() == glslang::EOpArrayLength) {
1050 // Quite special; won't want to evaluate the operand.
1051
1052 // Normal .length() would have been constant folded by the front-end.
1053 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001054 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001055 assert(node->getOperand()->getType().isRuntimeSizedArray());
1056 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1057 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001058 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1059 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001060
1061 builder.clearAccessChain();
1062 builder.setAccessChainRValue(length);
1063
1064 return false;
1065 }
1066
John Kessenichfc51d282015-08-19 13:34:18 -06001067 // Start by evaluating the operand
1068
John Kessenich140f3df2015-06-26 16:58:36 -06001069 builder.clearAccessChain();
1070 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001071
Rex Xufc618912015-09-09 16:42:49 +08001072 spv::Id operand = spv::NoResult;
1073
1074 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1075 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001076 node->getOp() == glslang::EOpAtomicCounter ||
1077 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001078 operand = builder.accessChainGetLValue(); // Special case l-value operands
1079 else
John Kessenich32cfd492016-02-02 12:37:46 -07001080 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001081
1082 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001083 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001084
1085 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001086 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001087 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001088
1089 // if not, then possibly an operation
1090 if (! result)
qining25262b32016-05-06 17:25:16 -04001091 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001092
1093 if (result) {
1094 builder.clearAccessChain();
1095 builder.setAccessChainRValue(result);
1096
1097 return false; // done with this node
1098 }
1099
1100 // it must be a special case, check...
1101 switch (node->getOp()) {
1102 case glslang::EOpPostIncrement:
1103 case glslang::EOpPostDecrement:
1104 case glslang::EOpPreIncrement:
1105 case glslang::EOpPreDecrement:
1106 {
1107 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001108 spv::Id one = 0;
1109 if (node->getBasicType() == glslang::EbtFloat)
1110 one = builder.makeFloatConstant(1.0F);
1111 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1112 one = builder.makeInt64Constant(1);
1113 else
1114 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001115 glslang::TOperator op;
1116 if (node->getOp() == glslang::EOpPreIncrement ||
1117 node->getOp() == glslang::EOpPostIncrement)
1118 op = glslang::EOpAdd;
1119 else
1120 op = glslang::EOpSub;
1121
qining25262b32016-05-06 17:25:16 -04001122 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1123 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001124 convertGlslangToSpvType(node->getType()), operand, one,
1125 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001126 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001127
1128 // The result of operation is always stored, but conditionally the
1129 // consumed result. The consumed result is always an r-value.
1130 builder.accessChainStore(result);
1131 builder.clearAccessChain();
1132 if (node->getOp() == glslang::EOpPreIncrement ||
1133 node->getOp() == glslang::EOpPreDecrement)
1134 builder.setAccessChainRValue(result);
1135 else
1136 builder.setAccessChainRValue(operand);
1137 }
1138
1139 return false;
1140
1141 case glslang::EOpEmitStreamVertex:
1142 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1143 return false;
1144 case glslang::EOpEndStreamPrimitive:
1145 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1146 return false;
1147
1148 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001149 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001150 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001151 }
John Kessenich140f3df2015-06-26 16:58:36 -06001152}
1153
1154bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1155{
qining27e04a02016-04-14 16:40:20 -04001156 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1157 if (node->getType().getQualifier().isSpecConstant())
1158 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1159
John Kessenichfc51d282015-08-19 13:34:18 -06001160 spv::Id result = spv::NoResult;
1161
1162 // try texturing
1163 result = createImageTextureFunctionCall(node);
1164 if (result != spv::NoResult) {
1165 builder.clearAccessChain();
1166 builder.setAccessChainRValue(result);
1167
1168 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001169 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001170 // "imageStore" is a special case, which has no result
1171 return false;
1172 }
John Kessenichfc51d282015-08-19 13:34:18 -06001173
John Kessenich140f3df2015-06-26 16:58:36 -06001174 glslang::TOperator binOp = glslang::EOpNull;
1175 bool reduceComparison = true;
1176 bool isMatrix = false;
1177 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001178 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001179
1180 assert(node->getOp());
1181
1182 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1183
1184 switch (node->getOp()) {
1185 case glslang::EOpSequence:
1186 {
1187 if (preVisit)
1188 ++sequenceDepth;
1189 else
1190 --sequenceDepth;
1191
1192 if (sequenceDepth == 1) {
1193 // If this is the parent node of all the functions, we want to see them
1194 // early, so all call points have actual SPIR-V functions to reference.
1195 // In all cases, still let the traverser visit the children for us.
1196 makeFunctions(node->getAsAggregate()->getSequence());
1197
1198 // Also, we want all globals initializers to go into the entry of main(), before
1199 // anything else gets there, so visit out of order, doing them all now.
1200 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1201
1202 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1203 // so do them manually.
1204 visitFunctions(node->getAsAggregate()->getSequence());
1205
1206 return false;
1207 }
1208
1209 return true;
1210 }
1211 case glslang::EOpLinkerObjects:
1212 {
1213 if (visit == glslang::EvPreVisit)
1214 linkageOnly = true;
1215 else
1216 linkageOnly = false;
1217
1218 return true;
1219 }
1220 case glslang::EOpComma:
1221 {
1222 // processing from left to right naturally leaves the right-most
1223 // lying around in the access chain
1224 glslang::TIntermSequence& glslangOperands = node->getSequence();
1225 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1226 glslangOperands[i]->traverse(this);
1227
1228 return false;
1229 }
1230 case glslang::EOpFunction:
1231 if (visit == glslang::EvPreVisit) {
1232 if (isShaderEntrypoint(node)) {
1233 inMain = true;
1234 builder.setBuildPoint(shaderEntry->getLastBlock());
1235 } else {
1236 handleFunctionEntry(node);
1237 }
1238 } else {
1239 if (inMain)
1240 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001241 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001242 inMain = false;
1243 }
1244
1245 return true;
1246 case glslang::EOpParameters:
1247 // Parameters will have been consumed by EOpFunction processing, but not
1248 // the body, so we still visited the function node's children, making this
1249 // child redundant.
1250 return false;
1251 case glslang::EOpFunctionCall:
1252 {
1253 if (node->isUserDefined())
1254 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001255 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1256 if (result) {
1257 builder.clearAccessChain();
1258 builder.setAccessChainRValue(result);
1259 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001260 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001261
1262 return false;
1263 }
1264 case glslang::EOpConstructMat2x2:
1265 case glslang::EOpConstructMat2x3:
1266 case glslang::EOpConstructMat2x4:
1267 case glslang::EOpConstructMat3x2:
1268 case glslang::EOpConstructMat3x3:
1269 case glslang::EOpConstructMat3x4:
1270 case glslang::EOpConstructMat4x2:
1271 case glslang::EOpConstructMat4x3:
1272 case glslang::EOpConstructMat4x4:
1273 case glslang::EOpConstructDMat2x2:
1274 case glslang::EOpConstructDMat2x3:
1275 case glslang::EOpConstructDMat2x4:
1276 case glslang::EOpConstructDMat3x2:
1277 case glslang::EOpConstructDMat3x3:
1278 case glslang::EOpConstructDMat3x4:
1279 case glslang::EOpConstructDMat4x2:
1280 case glslang::EOpConstructDMat4x3:
1281 case glslang::EOpConstructDMat4x4:
1282 isMatrix = true;
1283 // fall through
1284 case glslang::EOpConstructFloat:
1285 case glslang::EOpConstructVec2:
1286 case glslang::EOpConstructVec3:
1287 case glslang::EOpConstructVec4:
1288 case glslang::EOpConstructDouble:
1289 case glslang::EOpConstructDVec2:
1290 case glslang::EOpConstructDVec3:
1291 case glslang::EOpConstructDVec4:
1292 case glslang::EOpConstructBool:
1293 case glslang::EOpConstructBVec2:
1294 case glslang::EOpConstructBVec3:
1295 case glslang::EOpConstructBVec4:
1296 case glslang::EOpConstructInt:
1297 case glslang::EOpConstructIVec2:
1298 case glslang::EOpConstructIVec3:
1299 case glslang::EOpConstructIVec4:
1300 case glslang::EOpConstructUint:
1301 case glslang::EOpConstructUVec2:
1302 case glslang::EOpConstructUVec3:
1303 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001304 case glslang::EOpConstructInt64:
1305 case glslang::EOpConstructI64Vec2:
1306 case glslang::EOpConstructI64Vec3:
1307 case glslang::EOpConstructI64Vec4:
1308 case glslang::EOpConstructUint64:
1309 case glslang::EOpConstructU64Vec2:
1310 case glslang::EOpConstructU64Vec3:
1311 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001312 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001313 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001314 {
1315 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001316 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1318 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001319 if (node->getOp() == glslang::EOpConstructTextureSampler)
1320 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1321 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001322 std::vector<spv::Id> constituents;
1323 for (int c = 0; c < (int)arguments.size(); ++c)
1324 constituents.push_back(arguments[c]);
1325 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001326 } else if (isMatrix)
1327 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1328 else
1329 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001330
1331 builder.clearAccessChain();
1332 builder.setAccessChainRValue(constructed);
1333
1334 return false;
1335 }
1336
1337 // These six are component-wise compares with component-wise results.
1338 // Forward on to createBinaryOperation(), requesting a vector result.
1339 case glslang::EOpLessThan:
1340 case glslang::EOpGreaterThan:
1341 case glslang::EOpLessThanEqual:
1342 case glslang::EOpGreaterThanEqual:
1343 case glslang::EOpVectorEqual:
1344 case glslang::EOpVectorNotEqual:
1345 {
1346 // Map the operation to a binary
1347 binOp = node->getOp();
1348 reduceComparison = false;
1349 switch (node->getOp()) {
1350 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1351 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1352 default: binOp = node->getOp(); break;
1353 }
1354
1355 break;
1356 }
1357 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001358 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001359 binOp = glslang::EOpMul;
1360 break;
1361 case glslang::EOpOuterProduct:
1362 // two vectors multiplied to make a matrix
1363 binOp = glslang::EOpOuterProduct;
1364 break;
1365 case glslang::EOpDot:
1366 {
qining25262b32016-05-06 17:25:16 -04001367 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001368 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001369 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001370 binOp = glslang::EOpMul;
1371 break;
1372 }
1373 case glslang::EOpMod:
1374 // when an aggregate, this is the floating-point mod built-in function,
1375 // which can be emitted by the one in createBinaryOperation()
1376 binOp = glslang::EOpMod;
1377 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001378 case glslang::EOpEmitVertex:
1379 case glslang::EOpEndPrimitive:
1380 case glslang::EOpBarrier:
1381 case glslang::EOpMemoryBarrier:
1382 case glslang::EOpMemoryBarrierAtomicCounter:
1383 case glslang::EOpMemoryBarrierBuffer:
1384 case glslang::EOpMemoryBarrierImage:
1385 case glslang::EOpMemoryBarrierShared:
1386 case glslang::EOpGroupMemoryBarrier:
1387 noReturnValue = true;
1388 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1389 break;
1390
John Kessenich426394d2015-07-23 10:22:48 -06001391 case glslang::EOpAtomicAdd:
1392 case glslang::EOpAtomicMin:
1393 case glslang::EOpAtomicMax:
1394 case glslang::EOpAtomicAnd:
1395 case glslang::EOpAtomicOr:
1396 case glslang::EOpAtomicXor:
1397 case glslang::EOpAtomicExchange:
1398 case glslang::EOpAtomicCompSwap:
1399 atomic = true;
1400 break;
1401
John Kessenich140f3df2015-06-26 16:58:36 -06001402 default:
1403 break;
1404 }
1405
1406 //
1407 // See if it maps to a regular operation.
1408 //
John Kessenich140f3df2015-06-26 16:58:36 -06001409 if (binOp != glslang::EOpNull) {
1410 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1411 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1412 assert(left && right);
1413
1414 builder.clearAccessChain();
1415 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001416 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001417
1418 builder.clearAccessChain();
1419 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001420 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001421
qining25262b32016-05-06 17:25:16 -04001422 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1423 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001424 left->getType().getBasicType(), reduceComparison);
1425
1426 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001427 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 builder.clearAccessChain();
1429 builder.setAccessChainRValue(result);
1430
1431 return false;
1432 }
1433
John Kessenich426394d2015-07-23 10:22:48 -06001434 //
1435 // Create the list of operands.
1436 //
John Kessenich140f3df2015-06-26 16:58:36 -06001437 glslang::TIntermSequence& glslangOperands = node->getSequence();
1438 std::vector<spv::Id> operands;
1439 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1440 builder.clearAccessChain();
1441 glslangOperands[arg]->traverse(this);
1442
1443 // special case l-value operands; there are just a few
1444 bool lvalue = false;
1445 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001446 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001447 case glslang::EOpModf:
1448 if (arg == 1)
1449 lvalue = true;
1450 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001451 case glslang::EOpInterpolateAtSample:
1452 case glslang::EOpInterpolateAtOffset:
1453 if (arg == 0)
1454 lvalue = true;
1455 break;
Rex Xud4782c12015-09-06 16:30:11 +08001456 case glslang::EOpAtomicAdd:
1457 case glslang::EOpAtomicMin:
1458 case glslang::EOpAtomicMax:
1459 case glslang::EOpAtomicAnd:
1460 case glslang::EOpAtomicOr:
1461 case glslang::EOpAtomicXor:
1462 case glslang::EOpAtomicExchange:
1463 case glslang::EOpAtomicCompSwap:
1464 if (arg == 0)
1465 lvalue = true;
1466 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001467 case glslang::EOpAddCarry:
1468 case glslang::EOpSubBorrow:
1469 if (arg == 2)
1470 lvalue = true;
1471 break;
1472 case glslang::EOpUMulExtended:
1473 case glslang::EOpIMulExtended:
1474 if (arg >= 2)
1475 lvalue = true;
1476 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001477 default:
1478 break;
1479 }
1480 if (lvalue)
1481 operands.push_back(builder.accessChainGetLValue());
1482 else
John Kessenich32cfd492016-02-02 12:37:46 -07001483 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001484 }
John Kessenich426394d2015-07-23 10:22:48 -06001485
1486 if (atomic) {
1487 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001488 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001489 } else {
1490 // Pass through to generic operations.
1491 switch (glslangOperands.size()) {
1492 case 0:
1493 result = createNoArgOperation(node->getOp());
1494 break;
1495 case 1:
qining25262b32016-05-06 17:25:16 -04001496 result = createUnaryOperation(
1497 node->getOp(), precision,
1498 TranslateNoContractionDecoration(node->getType().getQualifier()),
1499 convertGlslangToSpvType(node->getType()), operands.front(),
1500 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001501 break;
1502 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001503 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001504 break;
1505 }
John Kessenich140f3df2015-06-26 16:58:36 -06001506 }
1507
1508 if (noReturnValue)
1509 return false;
1510
1511 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001512 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001513 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001514 } else {
1515 builder.clearAccessChain();
1516 builder.setAccessChainRValue(result);
1517 return false;
1518 }
1519}
1520
1521bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1522{
1523 // This path handles both if-then-else and ?:
1524 // The if-then-else has a node type of void, while
1525 // ?: has a non-void node type
1526 spv::Id result = 0;
1527 if (node->getBasicType() != glslang::EbtVoid) {
1528 // don't handle this as just on-the-fly temporaries, because there will be two names
1529 // and better to leave SSA to later passes
1530 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1531 }
1532
1533 // emit the condition before doing anything with selection
1534 node->getCondition()->traverse(this);
1535
1536 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001537 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001538
1539 if (node->getTrueBlock()) {
1540 // emit the "then" statement
1541 node->getTrueBlock()->traverse(this);
1542 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001543 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001544 }
1545
1546 if (node->getFalseBlock()) {
1547 ifBuilder.makeBeginElse();
1548 // emit the "else" statement
1549 node->getFalseBlock()->traverse(this);
1550 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001551 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001552 }
1553
1554 ifBuilder.makeEndIf();
1555
1556 if (result) {
1557 // GLSL only has r-values as the result of a :?, but
1558 // if we have an l-value, that can be more efficient if it will
1559 // become the base of a complex r-value expression, because the
1560 // next layer copies r-values into memory to use the access-chain mechanism
1561 builder.clearAccessChain();
1562 builder.setAccessChainLValue(result);
1563 }
1564
1565 return false;
1566}
1567
1568bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1569{
1570 // emit and get the condition before doing anything with switch
1571 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001572 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001573
1574 // browse the children to sort out code segments
1575 int defaultSegment = -1;
1576 std::vector<TIntermNode*> codeSegments;
1577 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1578 std::vector<int> caseValues;
1579 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1580 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1581 TIntermNode* child = *c;
1582 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001583 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001584 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001585 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001586 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1587 } else
1588 codeSegments.push_back(child);
1589 }
1590
qining25262b32016-05-06 17:25:16 -04001591 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001592 // statements between the last case and the end of the switch statement
1593 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1594 (int)codeSegments.size() == defaultSegment)
1595 codeSegments.push_back(nullptr);
1596
1597 // make the switch statement
1598 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001599 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001600
1601 // emit all the code in the segments
1602 breakForLoop.push(false);
1603 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1604 builder.nextSwitchSegment(segmentBlocks, s);
1605 if (codeSegments[s])
1606 codeSegments[s]->traverse(this);
1607 else
1608 builder.addSwitchBreak();
1609 }
1610 breakForLoop.pop();
1611
1612 builder.endSwitch(segmentBlocks);
1613
1614 return false;
1615}
1616
1617void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1618{
1619 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001620 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001621
1622 builder.clearAccessChain();
1623 builder.setAccessChainRValue(constant);
1624}
1625
1626bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1627{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001628 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001629 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001630 // Spec requires back edges to target header blocks, and every header block
1631 // must dominate its merge block. Make a header block first to ensure these
1632 // conditions are met. By definition, it will contain OpLoopMerge, followed
1633 // by a block-ending branch. But we don't want to put any other body/test
1634 // instructions in it, since the body/test may have arbitrary instructions,
1635 // including merges of its own.
1636 builder.setBuildPoint(&blocks.head);
1637 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001638 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001639 spv::Block& test = builder.makeNewBlock();
1640 builder.createBranch(&test);
1641
1642 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001643 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001644 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001645 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001646 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1647
1648 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001649 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001650 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001651 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001652 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001653 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654
1655 builder.setBuildPoint(&blocks.continue_target);
1656 if (node->getTerminal())
1657 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001658 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001659 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001660 builder.createBranch(&blocks.body);
1661
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001662 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001663 builder.setBuildPoint(&blocks.body);
1664 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001665 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001666 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001667 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001668
1669 builder.setBuildPoint(&blocks.continue_target);
1670 if (node->getTerminal())
1671 node->getTerminal()->traverse(this);
1672 if (node->getTest()) {
1673 node->getTest()->traverse(this);
1674 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001675 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001676 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001677 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001678 // TODO: unless there was a break/return/discard instruction
1679 // somewhere in the body, this is an infinite loop, so we should
1680 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001681 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001682 }
John Kessenich140f3df2015-06-26 16:58:36 -06001683 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001684 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001685 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001686 return false;
1687}
1688
1689bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1690{
1691 if (node->getExpression())
1692 node->getExpression()->traverse(this);
1693
1694 switch (node->getFlowOp()) {
1695 case glslang::EOpKill:
1696 builder.makeDiscard();
1697 break;
1698 case glslang::EOpBreak:
1699 if (breakForLoop.top())
1700 builder.createLoopExit();
1701 else
1702 builder.addSwitchBreak();
1703 break;
1704 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001705 builder.createLoopContinue();
1706 break;
1707 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001708 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001709 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001710 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001711 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001712
1713 builder.clearAccessChain();
1714 break;
1715
1716 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001717 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001718 break;
1719 }
1720
1721 return false;
1722}
1723
1724spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1725{
qining25262b32016-05-06 17:25:16 -04001726 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001727 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001728 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001729 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001730 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001731 }
1732
1733 // Now, handle actual variables
1734 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1735 spv::Id spvType = convertGlslangToSpvType(node->getType());
1736
1737 const char* name = node->getName().c_str();
1738 if (glslang::IsAnonymous(name))
1739 name = "";
1740
1741 return builder.createVariable(storageClass, spvType, name);
1742}
1743
1744// Return type Id of the sampled type.
1745spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1746{
1747 switch (sampler.type) {
1748 case glslang::EbtFloat: return builder.makeFloatType(32);
1749 case glslang::EbtInt: return builder.makeIntType(32);
1750 case glslang::EbtUint: return builder.makeUintType(32);
1751 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001752 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001753 return builder.makeFloatType(32);
1754 }
1755}
1756
John Kessenich3ac051e2015-12-20 11:29:16 -07001757// Convert from a glslang type to an SPV type, by calling into a
1758// recursive version of this function. This establishes the inherited
1759// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001760spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1761{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001762 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001763}
1764
1765// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001766// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001767spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001768{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001769 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001770
1771 switch (type.getBasicType()) {
1772 case glslang::EbtVoid:
1773 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001774 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001775 break;
1776 case glslang::EbtFloat:
1777 spvType = builder.makeFloatType(32);
1778 break;
1779 case glslang::EbtDouble:
1780 spvType = builder.makeFloatType(64);
1781 break;
1782 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001783 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1784 // a 32-bit int where non-0 means true.
1785 if (explicitLayout != glslang::ElpNone)
1786 spvType = builder.makeUintType(32);
1787 else
1788 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001789 break;
1790 case glslang::EbtInt:
1791 spvType = builder.makeIntType(32);
1792 break;
1793 case glslang::EbtUint:
1794 spvType = builder.makeUintType(32);
1795 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001796 case glslang::EbtInt64:
1797 builder.addCapability(spv::CapabilityInt64);
1798 spvType = builder.makeIntType(64);
1799 break;
1800 case glslang::EbtUint64:
1801 builder.addCapability(spv::CapabilityInt64);
1802 spvType = builder.makeUintType(64);
1803 break;
John Kessenich426394d2015-07-23 10:22:48 -06001804 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001805 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 -06001806 spvType = builder.makeUintType(32);
1807 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001808 case glslang::EbtSampler:
1809 {
1810 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001811 if (sampler.sampler) {
1812 // pure sampler
1813 spvType = builder.makeSamplerType();
1814 } else {
1815 // an image is present, make its type
1816 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1817 sampler.image ? 2 : 1, TranslateImageFormat(type));
1818 if (sampler.combined) {
1819 // already has both image and sampler, make the combined type
1820 spvType = builder.makeSampledImageType(spvType);
1821 }
John Kessenich55e7d112015-11-15 21:33:39 -07001822 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001823 }
John Kessenich140f3df2015-06-26 16:58:36 -06001824 break;
1825 case glslang::EbtStruct:
1826 case glslang::EbtBlock:
1827 {
1828 // If we've seen this struct type, return it
1829 const glslang::TTypeList* glslangStruct = type.getStruct();
1830 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001831
1832 // Try to share structs for different layouts, but not yet for other
1833 // kinds of qualification (primarily not yet including interpolant qualification).
1834 if (! HasNonLayoutQualifiers(qualifier))
1835 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1836 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001837 break;
1838
1839 // else, we haven't seen it...
1840
1841 // Create a vector of struct types for SPIR-V to consume
1842 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1843 if (type.getBasicType() == glslang::EbtBlock)
1844 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001845 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001846 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1847 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1848 if (glslangType.hiddenMember()) {
1849 ++memberDelta;
1850 if (type.getBasicType() == glslang::EbtBlock)
1851 memberRemapper[glslangStruct][i] = -1;
1852 } else {
1853 if (type.getBasicType() == glslang::EbtBlock)
1854 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001855 // modify just this child's view of the qualifier
1856 glslang::TQualifier subQualifier = glslangType.getQualifier();
1857 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001858
1859 // manually inherit location; it's more complex
1860 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1861 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1862 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001863 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001864
1865 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001866 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001867 }
1868 }
1869
1870 // Make the SPIR-V type
1871 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001872 if (! HasNonLayoutQualifiers(qualifier))
1873 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001874
1875 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001876 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001877 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001878 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1879 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1880 int member = i;
1881 if (type.getBasicType() == glslang::EbtBlock)
1882 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001883
John Kesseniche0b6cad2015-12-24 10:30:13 -07001884 // modify just this child's view of the qualifier
1885 glslang::TQualifier subQualifier = glslangType.getQualifier();
1886 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001887
John Kessenich140f3df2015-06-26 16:58:36 -06001888 // using -1 above to indicate a hidden member
1889 if (member >= 0) {
1890 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001892 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
scygan8add1512016-05-06 16:54:54 +02001893 // Add interpolation decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001894 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001895 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1896 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001897 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001898
Rex Xu1da878f2016-02-21 20:59:01 +08001899 if (qualifier.storage == glslang::EvqBuffer) {
1900 std::vector<spv::Decoration> memory;
1901 TranslateMemoryDecoration(subQualifier, memory);
1902 for (unsigned int i = 0; i < memory.size(); ++i)
1903 addMemberDecoration(spvType, member, memory[i]);
1904 }
1905
John Kessenich09677482016-02-19 12:21:50 -07001906 // compute location decoration; tricky based on whether inheritance is at play
1907 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1908 // probably move to the linker stage of the front end proper, and just have the
1909 // answer sitting already distributed throughout the individual member locations.
1910 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001911 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001912 // struct members should not have explicit locations
1913 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001914 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001915 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001916 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1917 // The members, and their nested types, must not themselves have Location decorations.
1918 }
John Kessenich09677482016-02-19 12:21:50 -07001919 else if (qualifier.hasLocation()) // inheritance
1920 location = qualifier.layoutLocation + locationOffset;
1921 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001922 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001923 if (location >= 0)
1924 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1925
1926 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001927 if (glslangType.getQualifier().hasComponent())
1928 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1929 if (glslangType.getQualifier().hasXfbOffset())
1930 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001931 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001932 // figure out what to do with offset, which is accumulating
1933 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001934 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001935 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001936 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001937 offset = nextOffset;
1938 }
John Kessenich140f3df2015-06-26 16:58:36 -06001939
John Kessenichf85e8062015-12-19 13:57:10 -07001940 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001941 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001942
John Kessenich140f3df2015-06-26 16:58:36 -06001943 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001944 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001945 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001946 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001947 }
1948 }
1949
1950 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001951 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001952 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001953 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001954 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001955 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001956 }
John Kessenich140f3df2015-06-26 16:58:36 -06001957 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001958 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001959 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001960 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001961 if (type.getQualifier().hasXfbBuffer())
1962 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1963 }
scygan2c864272016-05-18 18:09:17 +02001964
1965 if (type.getBasicType() != glslang::EbtBlock && (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut))
1966 {
1967 // The layout of a structure type used as an Input or Output depends on whether it is also a Block (i.e. has a Block decoration).
1968 // If it is a not a Block, then the structure type must have a Location decoration.
1969 if (type.getQualifier().hasLocation())
1970 builder.addDecoration(spvType, spv::DecorationLocation, type.getQualifier().layoutLocation);
1971 }
John Kessenich140f3df2015-06-26 16:58:36 -06001972 }
1973 break;
1974 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001975 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001976 break;
1977 }
1978
1979 if (type.isMatrix())
1980 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1981 else {
1982 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1983 if (type.getVectorSize() > 1)
1984 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1985 }
1986
1987 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001988 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1989
John Kessenichc9a80832015-09-12 12:17:44 -06001990 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001991 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001992 // We need to decorate array strides for types needing explicit layout, except blocks.
1993 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001994 // Use a dummy glslang type for querying internal strides of
1995 // arrays of arrays, but using just a one-dimensional array.
1996 glslang::TType simpleArrayType(type, 0); // deference type of the array
1997 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1998 simpleArrayType.getArraySizes().dereference();
1999
2000 // Will compute the higher-order strides here, rather than making a whole
2001 // pile of types and doing repetitive recursion on their contents.
2002 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2003 }
John Kessenichf8842e52016-01-04 19:22:56 -07002004
2005 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002006 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002007 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002008 if (stride > 0)
2009 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002010 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002011 }
2012 } else {
2013 // single-dimensional array, and don't yet have stride
2014
John Kessenichf8842e52016-01-04 19:22:56 -07002015 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002016 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2017 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002018 }
John Kessenich31ed4832015-09-09 17:51:38 -06002019
John Kessenichc9a80832015-09-12 12:17:44 -06002020 // Do the outer dimension, which might not be known for a runtime-sized array
2021 if (type.isRuntimeSizedArray()) {
2022 spvType = builder.makeRuntimeArray(spvType);
2023 } else {
2024 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002025 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002026 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002027 if (stride > 0)
2028 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002029 }
2030
2031 return spvType;
2032}
2033
John Kessenich6c292d32016-02-15 20:58:50 -07002034// Turn the expression forming the array size into an id.
2035// This is not quite trivial, because of specialization constants.
2036// Sometimes, a raw constant is turned into an Id, and sometimes
2037// a specialization constant expression is.
2038spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2039{
2040 // First, see if this is sized with a node, meaning a specialization constant:
2041 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2042 if (specNode != nullptr) {
2043 builder.clearAccessChain();
2044 specNode->traverse(this);
2045 return accessChainLoad(specNode->getAsTyped()->getType());
2046 }
qining25262b32016-05-06 17:25:16 -04002047
John Kessenich6c292d32016-02-15 20:58:50 -07002048 // Otherwise, need a compile-time (front end) size, get it:
2049 int size = arraySizes.getDimSize(dim);
2050 assert(size > 0);
2051 return builder.makeUintConstant(size);
2052}
2053
John Kessenich103bef92016-02-08 21:38:15 -07002054// Wrap the builder's accessChainLoad to:
2055// - localize handling of RelaxedPrecision
2056// - use the SPIR-V inferred type instead of another conversion of the glslang type
2057// (avoids unnecessary work and possible type punning for structures)
2058// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002059spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2060{
John Kessenich103bef92016-02-08 21:38:15 -07002061 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2062 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2063
2064 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002065 if (type.getBasicType() == glslang::EbtBool) {
2066 if (builder.isScalarType(nominalTypeId)) {
2067 // Conversion for bool
2068 spv::Id boolType = builder.makeBoolType();
2069 if (nominalTypeId != boolType)
2070 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2071 } else if (builder.isVectorType(nominalTypeId)) {
2072 // Conversion for bvec
2073 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2074 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2075 if (nominalTypeId != bvecType)
2076 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2077 }
2078 }
John Kessenich103bef92016-02-08 21:38:15 -07002079
2080 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002081}
2082
Rex Xu27253232016-02-23 17:51:09 +08002083// Wrap the builder's accessChainStore to:
2084// - do conversion of concrete to abstract type
2085void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2086{
2087 // Need to convert to abstract types when necessary
2088 if (type.getBasicType() == glslang::EbtBool) {
2089 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2090
2091 if (builder.isScalarType(nominalTypeId)) {
2092 // Conversion for bool
2093 spv::Id boolType = builder.makeBoolType();
2094 if (nominalTypeId != boolType) {
2095 spv::Id zero = builder.makeUintConstant(0);
2096 spv::Id one = builder.makeUintConstant(1);
2097 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2098 }
2099 } else if (builder.isVectorType(nominalTypeId)) {
2100 // Conversion for bvec
2101 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2102 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2103 if (nominalTypeId != bvecType) {
2104 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2105 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2106 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2107 }
2108 }
2109 }
2110
2111 builder.accessChainStore(rvalue);
2112}
2113
John Kessenichf85e8062015-12-19 13:57:10 -07002114// Decide whether or not this type should be
2115// decorated with offsets and strides, and if so
2116// whether std140 or std430 rules should be applied.
2117glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002118{
John Kessenichf85e8062015-12-19 13:57:10 -07002119 // has to be a block
2120 if (type.getBasicType() != glslang::EbtBlock)
2121 return glslang::ElpNone;
2122
2123 // has to be a uniform or buffer block
2124 if (type.getQualifier().storage != glslang::EvqUniform &&
2125 type.getQualifier().storage != glslang::EvqBuffer)
2126 return glslang::ElpNone;
2127
2128 // return the layout to use
2129 switch (type.getQualifier().layoutPacking) {
2130 case glslang::ElpStd140:
2131 case glslang::ElpStd430:
2132 return type.getQualifier().layoutPacking;
2133 default:
2134 return glslang::ElpNone;
2135 }
John Kessenich31ed4832015-09-09 17:51:38 -06002136}
2137
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002138// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002139int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002140{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002141 int size;
John Kessenich49987892015-12-29 17:11:44 -07002142 int stride;
2143 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002144
2145 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002146}
2147
John Kessenich49987892015-12-29 17:11:44 -07002148// 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 -07002149// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002150int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002151{
John Kessenich49987892015-12-29 17:11:44 -07002152 glslang::TType elementType;
2153 elementType.shallowCopy(matrixType);
2154 elementType.clearArraySizes();
2155
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002156 int size;
John Kessenich49987892015-12-29 17:11:44 -07002157 int stride;
2158 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2159
2160 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002161}
2162
John Kessenich5e4b1242015-08-06 22:53:06 -06002163// Given a member type of a struct, realign the current offset for it, and compute
2164// the next (not yet aligned) offset for the next member, which will get aligned
2165// on the next call.
2166// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2167// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2168// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002169void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002170 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002171{
2172 // this will get a positive value when deemed necessary
2173 nextOffset = -1;
2174
John Kessenich5e4b1242015-08-06 22:53:06 -06002175 // override anything in currentOffset with user-set offset
2176 if (memberType.getQualifier().hasOffset())
2177 currentOffset = memberType.getQualifier().layoutOffset;
2178
2179 // It could be that current linker usage in glslang updated all the layoutOffset,
2180 // in which case the following code does not matter. But, that's not quite right
2181 // once cross-compilation unit GLSL validation is done, as the original user
2182 // settings are needed in layoutOffset, and then the following will come into play.
2183
John Kessenichf85e8062015-12-19 13:57:10 -07002184 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002185 if (! memberType.getQualifier().hasOffset())
2186 currentOffset = -1;
2187
2188 return;
2189 }
2190
John Kessenichf85e8062015-12-19 13:57:10 -07002191 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002192 if (currentOffset < 0)
2193 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002194
John Kessenich5e4b1242015-08-06 22:53:06 -06002195 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2196 // but possibly not yet correctly aligned.
2197
2198 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002199 int dummyStride;
2200 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002201 glslang::RoundToPow2(currentOffset, memberAlignment);
2202 nextOffset = currentOffset + memberSize;
2203}
2204
John Kessenichebb50532016-05-16 19:22:05 -06002205void TGlslangToSpvTraverser::declareClipCullCapability(const glslang::TTypeList& members, int member)
2206{
2207 if (members[member].type->getQualifier().builtIn == glslang::EbvClipDistance)
2208 builder.addCapability(spv::CapabilityClipDistance);
2209 if (members[member].type->getQualifier().builtIn == glslang::EbvCullDistance)
2210 builder.addCapability(spv::CapabilityCullDistance);
2211}
2212
John Kessenich140f3df2015-06-26 16:58:36 -06002213bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2214{
John Kessenich4d65ee32016-03-12 18:17:47 -07002215 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002216 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002217 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002218}
2219
2220// Make all the functions, skeletally, without actually visiting their bodies.
2221void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2222{
2223 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2224 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2225 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2226 continue;
2227
2228 // We're on a user function. Set up the basic interface for the function now,
2229 // so that it's available to call.
2230 // Translating the body will happen later.
2231 //
qining25262b32016-05-06 17:25:16 -04002232 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002233 // function. What it is an address of varies:
2234 //
2235 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2236 // so that write needs to be to a copy, hence the address of a copy works.
2237 //
2238 // - "const in" parameters can just be the r-value, as no writes need occur.
2239 //
2240 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2241 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2242
2243 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002244 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002245 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2246
2247 for (int p = 0; p < (int)parameters.size(); ++p) {
2248 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2249 spv::Id typeId = convertGlslangToSpvType(paramType);
2250 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2251 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2252 else
2253 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002254 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002255 paramTypes.push_back(typeId);
2256 }
2257
2258 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002259 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2260 convertGlslangToSpvType(glslFunction->getType()),
2261 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002262
2263 // Track function to emit/call later
2264 functionMap[glslFunction->getName().c_str()] = function;
2265
2266 // Set the parameter id's
2267 for (int p = 0; p < (int)parameters.size(); ++p) {
2268 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2269 // give a name too
2270 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2271 }
2272 }
2273}
2274
2275// Process all the initializers, while skipping the functions and link objects
2276void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2277{
2278 builder.setBuildPoint(shaderEntry->getLastBlock());
2279 for (int i = 0; i < (int)initializers.size(); ++i) {
2280 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2281 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2282
2283 // We're on a top-level node that's not a function. Treat as an initializer, whose
2284 // code goes into the beginning of main.
2285 initializer->traverse(this);
2286 }
2287 }
2288}
2289
2290// Process all the functions, while skipping initializers.
2291void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2292{
2293 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2294 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2295 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2296 node->traverse(this);
2297 }
2298}
2299
2300void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2301{
qining25262b32016-05-06 17:25:16 -04002302 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002303 // that called makeFunctions().
2304 spv::Function* function = functionMap[node->getName().c_str()];
2305 spv::Block* functionBlock = function->getEntryBlock();
2306 builder.setBuildPoint(functionBlock);
2307}
2308
Rex Xu04db3f52015-09-16 11:44:02 +08002309void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002310{
Rex Xufc618912015-09-09 16:42:49 +08002311 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002312
2313 glslang::TSampler sampler = {};
2314 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002315 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002316 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2317 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2318 }
2319
John Kessenich140f3df2015-06-26 16:58:36 -06002320 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2321 builder.clearAccessChain();
2322 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002323
2324 // Special case l-value operands
2325 bool lvalue = false;
2326 switch (node.getOp()) {
2327 case glslang::EOpImageAtomicAdd:
2328 case glslang::EOpImageAtomicMin:
2329 case glslang::EOpImageAtomicMax:
2330 case glslang::EOpImageAtomicAnd:
2331 case glslang::EOpImageAtomicOr:
2332 case glslang::EOpImageAtomicXor:
2333 case glslang::EOpImageAtomicExchange:
2334 case glslang::EOpImageAtomicCompSwap:
2335 if (i == 0)
2336 lvalue = true;
2337 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002338 case glslang::EOpSparseImageLoad:
2339 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2340 lvalue = true;
2341 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002342 case glslang::EOpSparseTexture:
2343 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2344 lvalue = true;
2345 break;
2346 case glslang::EOpSparseTextureClamp:
2347 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2348 lvalue = true;
2349 break;
2350 case glslang::EOpSparseTextureLod:
2351 case glslang::EOpSparseTextureOffset:
2352 if (i == 3)
2353 lvalue = true;
2354 break;
2355 case glslang::EOpSparseTextureFetch:
2356 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2357 lvalue = true;
2358 break;
2359 case glslang::EOpSparseTextureFetchOffset:
2360 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2361 lvalue = true;
2362 break;
2363 case glslang::EOpSparseTextureLodOffset:
2364 case glslang::EOpSparseTextureGrad:
2365 case glslang::EOpSparseTextureOffsetClamp:
2366 if (i == 4)
2367 lvalue = true;
2368 break;
2369 case glslang::EOpSparseTextureGradOffset:
2370 case glslang::EOpSparseTextureGradClamp:
2371 if (i == 5)
2372 lvalue = true;
2373 break;
2374 case glslang::EOpSparseTextureGradOffsetClamp:
2375 if (i == 6)
2376 lvalue = true;
2377 break;
2378 case glslang::EOpSparseTextureGather:
2379 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2380 lvalue = true;
2381 break;
2382 case glslang::EOpSparseTextureGatherOffset:
2383 case glslang::EOpSparseTextureGatherOffsets:
2384 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2385 lvalue = true;
2386 break;
Rex Xufc618912015-09-09 16:42:49 +08002387 default:
2388 break;
2389 }
2390
Rex Xu6b86d492015-09-16 17:48:22 +08002391 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002392 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002393 else
John Kessenich32cfd492016-02-02 12:37:46 -07002394 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002395 }
2396}
2397
John Kessenichfc51d282015-08-19 13:34:18 -06002398void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002399{
John Kessenichfc51d282015-08-19 13:34:18 -06002400 builder.clearAccessChain();
2401 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002402 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002403}
John Kessenich140f3df2015-06-26 16:58:36 -06002404
John Kessenichfc51d282015-08-19 13:34:18 -06002405spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2406{
Rex Xufc618912015-09-09 16:42:49 +08002407 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002408 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002409 }
2410
John Kessenichfc51d282015-08-19 13:34:18 -06002411 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002412 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2413 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2414 std::vector<spv::Id> arguments;
2415 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002416 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002417 else
2418 translateArguments(*node->getAsUnaryNode(), arguments);
2419 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2420
2421 spv::Builder::TextureParameters params = { };
2422 params.sampler = arguments[0];
2423
Rex Xu04db3f52015-09-16 11:44:02 +08002424 glslang::TCrackedTextureOp cracked;
2425 node->crackTexture(sampler, cracked);
2426
John Kessenichfc51d282015-08-19 13:34:18 -06002427 // Check for queries
2428 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002429 // a sampled image needs to have the image extracted first
2430 if (builder.isSampledImage(params.sampler))
2431 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002432 switch (node->getOp()) {
2433 case glslang::EOpImageQuerySize:
2434 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002435 if (arguments.size() > 1) {
2436 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002437 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002438 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002439 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002440 case glslang::EOpImageQuerySamples:
2441 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002442 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002443 case glslang::EOpTextureQueryLod:
2444 params.coords = arguments[1];
2445 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2446 case glslang::EOpTextureQueryLevels:
2447 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002448 case glslang::EOpSparseTexelsResident:
2449 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002450 default:
2451 assert(0);
2452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002453 }
John Kessenich140f3df2015-06-26 16:58:36 -06002454 }
2455
Rex Xufc618912015-09-09 16:42:49 +08002456 // Check for image functions other than queries
2457 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002458 std::vector<spv::Id> operands;
2459 auto opIt = arguments.begin();
2460 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002461
2462 // Handle subpass operations
2463 // TODO: GLSL should change to have the "MS" only on the type rather than the
2464 // built-in function.
2465 if (cracked.subpass) {
2466 // add on the (0,0) coordinate
2467 spv::Id zero = builder.makeIntConstant(0);
2468 std::vector<spv::Id> comps;
2469 comps.push_back(zero);
2470 comps.push_back(zero);
2471 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2472 if (sampler.ms) {
2473 operands.push_back(spv::ImageOperandsSampleMask);
2474 operands.push_back(*(opIt++));
2475 }
2476 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2477 }
2478
John Kessenich56bab042015-09-16 10:54:31 -06002479 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002480 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002481 if (sampler.ms) {
2482 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002483 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002484 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002485 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2486 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002487 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002488 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002489 if (sampler.ms) {
2490 operands.push_back(*(opIt + 1));
2491 operands.push_back(spv::ImageOperandsSampleMask);
2492 operands.push_back(*opIt);
2493 } else
2494 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002495 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002496 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2497 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002498 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002499 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2500 builder.addCapability(spv::CapabilitySparseResidency);
2501 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2502 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2503
2504 if (sampler.ms) {
2505 operands.push_back(spv::ImageOperandsSampleMask);
2506 operands.push_back(*opIt++);
2507 }
2508
2509 // Create the return type that was a special structure
2510 spv::Id texelOut = *opIt;
2511 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2512 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2513 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2514
2515 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2516
2517 // Decode the return type
2518 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2519 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002520 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002521 // Process image atomic operations
2522
2523 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2524 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002525 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002526
Rex Xufc618912015-09-09 16:42:49 +08002527 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002528 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002529
2530 std::vector<spv::Id> operands;
2531 operands.push_back(pointer);
2532 for (; opIt != arguments.end(); ++opIt)
2533 operands.push_back(*opIt);
2534
Rex Xu04db3f52015-09-16 11:44:02 +08002535 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002536 }
2537 }
2538
2539 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002540 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002541 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2542
John Kessenichfc51d282015-08-19 13:34:18 -06002543 // check for bias argument
2544 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002545 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002546 int nonBiasArgCount = 2;
2547 if (cracked.offset)
2548 ++nonBiasArgCount;
2549 if (cracked.grad)
2550 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002551 if (cracked.lodClamp)
2552 ++nonBiasArgCount;
2553 if (sparse)
2554 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002555
2556 if ((int)arguments.size() > nonBiasArgCount)
2557 bias = true;
2558 }
2559
John Kessenichfc51d282015-08-19 13:34:18 -06002560 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002561
John Kessenichfc51d282015-08-19 13:34:18 -06002562 params.coords = arguments[1];
2563 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002564 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002565
2566 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002567 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002568 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002569 ++extraArgs;
2570 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002571 params.Dref = arguments[2];
2572 ++extraArgs;
2573 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002574 std::vector<spv::Id> indexes;
2575 int comp;
2576 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002577 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002578 else
2579 comp = builder.getNumComponents(params.coords) - 1;
2580 indexes.push_back(comp);
2581 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2582 }
2583 if (cracked.lod) {
2584 params.lod = arguments[2];
2585 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002586 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2587 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2588 noImplicitLod = true;
2589 }
2590 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002591 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002592 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002593 }
2594 if (cracked.grad) {
2595 params.gradX = arguments[2 + extraArgs];
2596 params.gradY = arguments[3 + extraArgs];
2597 extraArgs += 2;
2598 }
John Kessenich55e7d112015-11-15 21:33:39 -07002599 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002600 params.offset = arguments[2 + extraArgs];
2601 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002602 } else if (cracked.offsets) {
2603 params.offsets = arguments[2 + extraArgs];
2604 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002605 }
Rex Xu48edadf2015-12-31 16:11:41 +08002606 if (cracked.lodClamp) {
2607 params.lodClamp = arguments[2 + extraArgs];
2608 ++extraArgs;
2609 }
2610 if (sparse) {
2611 params.texelOut = arguments[2 + extraArgs];
2612 ++extraArgs;
2613 }
John Kessenichfc51d282015-08-19 13:34:18 -06002614 if (bias) {
2615 params.bias = arguments[2 + extraArgs];
2616 ++extraArgs;
2617 }
John Kessenich55e7d112015-11-15 21:33:39 -07002618 if (cracked.gather && ! sampler.shadow) {
2619 // default component is 0, if missing, otherwise an argument
2620 if (2 + extraArgs < (int)arguments.size()) {
2621 params.comp = arguments[2 + extraArgs];
2622 ++extraArgs;
2623 } else {
2624 params.comp = builder.makeIntConstant(0);
2625 }
2626 }
John Kessenichfc51d282015-08-19 13:34:18 -06002627
John Kessenich019f08f2016-02-15 15:40:42 -07002628 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002629}
2630
2631spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2632{
2633 // Grab the function's pointer from the previously created function
2634 spv::Function* function = functionMap[node->getName().c_str()];
2635 if (! function)
2636 return 0;
2637
2638 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2639 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2640
2641 // See comments in makeFunctions() for details about the semantics for parameter passing.
2642 //
2643 // These imply we need a four step process:
2644 // 1. Evaluate the arguments
2645 // 2. Allocate and make copies of in, out, and inout arguments
2646 // 3. Make the call
2647 // 4. Copy back the results
2648
2649 // 1. Evaluate the arguments
2650 std::vector<spv::Builder::AccessChain> lValues;
2651 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002652 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002653 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2654 // build l-value
2655 builder.clearAccessChain();
2656 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002657 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002658 // keep outputs as l-values, evaluate input-only as r-values
2659 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2660 // save l-value
2661 lValues.push_back(builder.getAccessChain());
2662 } else {
2663 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002664 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002665 }
2666 }
2667
2668 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2669 // copy the original into that space.
2670 //
2671 // Also, build up the list of actual arguments to pass in for the call
2672 int lValueCount = 0;
2673 int rValueCount = 0;
2674 std::vector<spv::Id> spvArgs;
2675 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2676 spv::Id arg;
2677 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2678 // need space to hold the copy
2679 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2680 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2681 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2682 // need to copy the input into output space
2683 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002684 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002685 builder.createStore(copy, arg);
2686 }
2687 ++lValueCount;
2688 } else {
2689 arg = rValues[rValueCount];
2690 ++rValueCount;
2691 }
2692 spvArgs.push_back(arg);
2693 }
2694
2695 // 3. Make the call.
2696 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002697 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002698
2699 // 4. Copy back out an "out" arguments.
2700 lValueCount = 0;
2701 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2702 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2703 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2704 spv::Id copy = builder.createLoad(spvArgs[a]);
2705 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002706 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002707 }
2708 ++lValueCount;
2709 }
2710 }
2711
2712 return result;
2713}
2714
2715// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002716spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2717 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002718 spv::Id typeId, spv::Id left, spv::Id right,
2719 glslang::TBasicType typeProxy, bool reduceComparison)
2720{
Rex Xu8ff43de2016-04-22 16:51:45 +08002721 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002722 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002723 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002724
2725 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002726 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002727 bool comparison = false;
2728
2729 switch (op) {
2730 case glslang::EOpAdd:
2731 case glslang::EOpAddAssign:
2732 if (isFloat)
2733 binOp = spv::OpFAdd;
2734 else
2735 binOp = spv::OpIAdd;
2736 break;
2737 case glslang::EOpSub:
2738 case glslang::EOpSubAssign:
2739 if (isFloat)
2740 binOp = spv::OpFSub;
2741 else
2742 binOp = spv::OpISub;
2743 break;
2744 case glslang::EOpMul:
2745 case glslang::EOpMulAssign:
2746 if (isFloat)
2747 binOp = spv::OpFMul;
2748 else
2749 binOp = spv::OpIMul;
2750 break;
2751 case glslang::EOpVectorTimesScalar:
2752 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002753 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002754 if (builder.isVector(right))
2755 std::swap(left, right);
2756 assert(builder.isScalar(right));
2757 needMatchingVectors = false;
2758 binOp = spv::OpVectorTimesScalar;
2759 } else
2760 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002761 break;
2762 case glslang::EOpVectorTimesMatrix:
2763 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002764 binOp = spv::OpVectorTimesMatrix;
2765 break;
2766 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002767 binOp = spv::OpMatrixTimesVector;
2768 break;
2769 case glslang::EOpMatrixTimesScalar:
2770 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002771 binOp = spv::OpMatrixTimesScalar;
2772 break;
2773 case glslang::EOpMatrixTimesMatrix:
2774 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002775 binOp = spv::OpMatrixTimesMatrix;
2776 break;
2777 case glslang::EOpOuterProduct:
2778 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002779 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002780 break;
2781
2782 case glslang::EOpDiv:
2783 case glslang::EOpDivAssign:
2784 if (isFloat)
2785 binOp = spv::OpFDiv;
2786 else if (isUnsigned)
2787 binOp = spv::OpUDiv;
2788 else
2789 binOp = spv::OpSDiv;
2790 break;
2791 case glslang::EOpMod:
2792 case glslang::EOpModAssign:
2793 if (isFloat)
2794 binOp = spv::OpFMod;
2795 else if (isUnsigned)
2796 binOp = spv::OpUMod;
2797 else
2798 binOp = spv::OpSMod;
2799 break;
2800 case glslang::EOpRightShift:
2801 case glslang::EOpRightShiftAssign:
2802 if (isUnsigned)
2803 binOp = spv::OpShiftRightLogical;
2804 else
2805 binOp = spv::OpShiftRightArithmetic;
2806 break;
2807 case glslang::EOpLeftShift:
2808 case glslang::EOpLeftShiftAssign:
2809 binOp = spv::OpShiftLeftLogical;
2810 break;
2811 case glslang::EOpAnd:
2812 case glslang::EOpAndAssign:
2813 binOp = spv::OpBitwiseAnd;
2814 break;
2815 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002816 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002817 binOp = spv::OpLogicalAnd;
2818 break;
2819 case glslang::EOpInclusiveOr:
2820 case glslang::EOpInclusiveOrAssign:
2821 binOp = spv::OpBitwiseOr;
2822 break;
2823 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002824 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 binOp = spv::OpLogicalOr;
2826 break;
2827 case glslang::EOpExclusiveOr:
2828 case glslang::EOpExclusiveOrAssign:
2829 binOp = spv::OpBitwiseXor;
2830 break;
2831 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002832 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002833 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002834 break;
2835
2836 case glslang::EOpLessThan:
2837 case glslang::EOpGreaterThan:
2838 case glslang::EOpLessThanEqual:
2839 case glslang::EOpGreaterThanEqual:
2840 case glslang::EOpEqual:
2841 case glslang::EOpNotEqual:
2842 case glslang::EOpVectorEqual:
2843 case glslang::EOpVectorNotEqual:
2844 comparison = true;
2845 break;
2846 default:
2847 break;
2848 }
2849
John Kessenich7c1aa102015-10-15 13:29:11 -06002850 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002851 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002852 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002853 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002854 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002855
2856 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002857 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002858 builder.promoteScalar(precision, left, right);
2859
qining25262b32016-05-06 17:25:16 -04002860 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2861 addDecoration(result, noContraction);
2862 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002863 }
2864
2865 if (! comparison)
2866 return 0;
2867
John Kessenich7c1aa102015-10-15 13:29:11 -06002868 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002869
2870 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2871 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2872
John Kessenich22118352015-12-21 20:54:09 -07002873 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002874 }
2875
2876 switch (op) {
2877 case glslang::EOpLessThan:
2878 if (isFloat)
2879 binOp = spv::OpFOrdLessThan;
2880 else if (isUnsigned)
2881 binOp = spv::OpULessThan;
2882 else
2883 binOp = spv::OpSLessThan;
2884 break;
2885 case glslang::EOpGreaterThan:
2886 if (isFloat)
2887 binOp = spv::OpFOrdGreaterThan;
2888 else if (isUnsigned)
2889 binOp = spv::OpUGreaterThan;
2890 else
2891 binOp = spv::OpSGreaterThan;
2892 break;
2893 case glslang::EOpLessThanEqual:
2894 if (isFloat)
2895 binOp = spv::OpFOrdLessThanEqual;
2896 else if (isUnsigned)
2897 binOp = spv::OpULessThanEqual;
2898 else
2899 binOp = spv::OpSLessThanEqual;
2900 break;
2901 case glslang::EOpGreaterThanEqual:
2902 if (isFloat)
2903 binOp = spv::OpFOrdGreaterThanEqual;
2904 else if (isUnsigned)
2905 binOp = spv::OpUGreaterThanEqual;
2906 else
2907 binOp = spv::OpSGreaterThanEqual;
2908 break;
2909 case glslang::EOpEqual:
2910 case glslang::EOpVectorEqual:
2911 if (isFloat)
2912 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002913 else if (isBool)
2914 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002915 else
2916 binOp = spv::OpIEqual;
2917 break;
2918 case glslang::EOpNotEqual:
2919 case glslang::EOpVectorNotEqual:
2920 if (isFloat)
2921 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002922 else if (isBool)
2923 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002924 else
2925 binOp = spv::OpINotEqual;
2926 break;
2927 default:
2928 break;
2929 }
2930
qining25262b32016-05-06 17:25:16 -04002931 if (binOp != spv::OpNop) {
2932 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2933 addDecoration(result, noContraction);
2934 return builder.setPrecision(result, precision);
2935 }
John Kessenich140f3df2015-06-26 16:58:36 -06002936
2937 return 0;
2938}
2939
John Kessenich04bb8a02015-12-12 12:28:14 -07002940//
2941// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2942// These can be any of:
2943//
2944// matrix * scalar
2945// scalar * matrix
2946// matrix * matrix linear algebraic
2947// matrix * vector
2948// vector * matrix
2949// matrix * matrix componentwise
2950// matrix op matrix op in {+, -, /}
2951// matrix op scalar op in {+, -, /}
2952// scalar op matrix op in {+, -, /}
2953//
qining25262b32016-05-06 17:25:16 -04002954spv::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 -07002955{
2956 bool firstClass = true;
2957
2958 // First, handle first-class matrix operations (* and matrix/scalar)
2959 switch (op) {
2960 case spv::OpFDiv:
2961 if (builder.isMatrix(left) && builder.isScalar(right)) {
2962 // turn matrix / scalar into a multiply...
2963 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2964 op = spv::OpMatrixTimesScalar;
2965 } else
2966 firstClass = false;
2967 break;
2968 case spv::OpMatrixTimesScalar:
2969 if (builder.isMatrix(right))
2970 std::swap(left, right);
2971 assert(builder.isScalar(right));
2972 break;
2973 case spv::OpVectorTimesMatrix:
2974 assert(builder.isVector(left));
2975 assert(builder.isMatrix(right));
2976 break;
2977 case spv::OpMatrixTimesVector:
2978 assert(builder.isMatrix(left));
2979 assert(builder.isVector(right));
2980 break;
2981 case spv::OpMatrixTimesMatrix:
2982 assert(builder.isMatrix(left));
2983 assert(builder.isMatrix(right));
2984 break;
2985 default:
2986 firstClass = false;
2987 break;
2988 }
2989
qining25262b32016-05-06 17:25:16 -04002990 if (firstClass) {
2991 spv::Id result = builder.createBinOp(op, typeId, left, right);
2992 addDecoration(result, noContraction);
2993 return builder.setPrecision(result, precision);
2994 }
John Kessenich04bb8a02015-12-12 12:28:14 -07002995
2996 // Handle component-wise +, -, *, and / for all combinations of type.
2997 // The result type of all of them is the same type as the (a) matrix operand.
2998 // The algorithm is to:
2999 // - break the matrix(es) into vectors
3000 // - smear any scalar to a vector
3001 // - do vector operations
3002 // - make a matrix out the vector results
3003 switch (op) {
3004 case spv::OpFAdd:
3005 case spv::OpFSub:
3006 case spv::OpFDiv:
3007 case spv::OpFMul:
3008 {
3009 // one time set up...
3010 bool leftMat = builder.isMatrix(left);
3011 bool rightMat = builder.isMatrix(right);
3012 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3013 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3014 spv::Id scalarType = builder.getScalarTypeId(typeId);
3015 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3016 std::vector<spv::Id> results;
3017 spv::Id smearVec = spv::NoResult;
3018 if (builder.isScalar(left))
3019 smearVec = builder.smearScalar(precision, left, vecType);
3020 else if (builder.isScalar(right))
3021 smearVec = builder.smearScalar(precision, right, vecType);
3022
3023 // do each vector op
3024 for (unsigned int c = 0; c < numCols; ++c) {
3025 std::vector<unsigned int> indexes;
3026 indexes.push_back(c);
3027 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3028 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003029 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3030 addDecoration(result, noContraction);
3031 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003032 }
3033
3034 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003035 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003036 }
3037 default:
3038 assert(0);
3039 return spv::NoResult;
3040 }
3041}
3042
qining25262b32016-05-06 17:25:16 -04003043spv::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 -06003044{
3045 spv::Op unaryOp = spv::OpNop;
3046 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003047 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003048 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003049
3050 switch (op) {
3051 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003052 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003053 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003054 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003055 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003056 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003057 unaryOp = spv::OpSNegate;
3058 break;
3059
3060 case glslang::EOpLogicalNot:
3061 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003062 unaryOp = spv::OpLogicalNot;
3063 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003064 case glslang::EOpBitwiseNot:
3065 unaryOp = spv::OpNot;
3066 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003067
John Kessenich140f3df2015-06-26 16:58:36 -06003068 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003069 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003070 break;
3071 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003072 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003073 break;
3074 case glslang::EOpTranspose:
3075 unaryOp = spv::OpTranspose;
3076 break;
3077
3078 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003079 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003080 break;
3081 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003082 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003083 break;
3084 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003086 break;
3087 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003088 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003089 break;
3090 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003091 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003092 break;
3093 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003094 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003095 break;
3096 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003097 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003098 break;
3099 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003100 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003101 break;
3102
3103 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003104 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003105 break;
3106 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003107 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003108 break;
3109 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003110 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003111 break;
3112 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003114 break;
3115 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003116 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003117 break;
3118 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003119 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121
3122 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128
3129 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003130 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003131 break;
3132 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003133 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003134 break;
3135 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003136 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003137 break;
3138 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003139 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003140 break;
3141 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003142 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003143 break;
3144 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003145 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003146 break;
3147
3148 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003149 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003152 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003153 break;
3154 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003155 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003161 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003162 break;
3163 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003164 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003165 break;
3166
3167 case glslang::EOpIsNan:
3168 unaryOp = spv::OpIsNan;
3169 break;
3170 case glslang::EOpIsInf:
3171 unaryOp = spv::OpIsInf;
3172 break;
3173
Rex Xucbc426e2015-12-15 16:03:10 +08003174 case glslang::EOpFloatBitsToInt:
3175 case glslang::EOpFloatBitsToUint:
3176 case glslang::EOpIntBitsToFloat:
3177 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003178 case glslang::EOpDoubleBitsToInt64:
3179 case glslang::EOpDoubleBitsToUint64:
3180 case glslang::EOpInt64BitsToDouble:
3181 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003182 unaryOp = spv::OpBitcast;
3183 break;
3184
John Kessenich140f3df2015-06-26 16:58:36 -06003185 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003186 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 break;
3188 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003189 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003190 break;
3191 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003193 break;
3194 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003195 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003196 break;
3197 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003198 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003202 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003203 case glslang::EOpPackSnorm4x8:
3204 libCall = spv::GLSLstd450PackSnorm4x8;
3205 break;
3206 case glslang::EOpUnpackSnorm4x8:
3207 libCall = spv::GLSLstd450UnpackSnorm4x8;
3208 break;
3209 case glslang::EOpPackUnorm4x8:
3210 libCall = spv::GLSLstd450PackUnorm4x8;
3211 break;
3212 case glslang::EOpUnpackUnorm4x8:
3213 libCall = spv::GLSLstd450UnpackUnorm4x8;
3214 break;
3215 case glslang::EOpPackDouble2x32:
3216 libCall = spv::GLSLstd450PackDouble2x32;
3217 break;
3218 case glslang::EOpUnpackDouble2x32:
3219 libCall = spv::GLSLstd450UnpackDouble2x32;
3220 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003221
Rex Xu8ff43de2016-04-22 16:51:45 +08003222 case glslang::EOpPackInt2x32:
3223 case glslang::EOpUnpackInt2x32:
3224 case glslang::EOpPackUint2x32:
3225 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003226 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003227 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3228 break;
3229
John Kessenich140f3df2015-06-26 16:58:36 -06003230 case glslang::EOpDPdx:
3231 unaryOp = spv::OpDPdx;
3232 break;
3233 case glslang::EOpDPdy:
3234 unaryOp = spv::OpDPdy;
3235 break;
3236 case glslang::EOpFwidth:
3237 unaryOp = spv::OpFwidth;
3238 break;
3239 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003240 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003241 unaryOp = spv::OpDPdxFine;
3242 break;
3243 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003244 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003245 unaryOp = spv::OpDPdyFine;
3246 break;
3247 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003248 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 unaryOp = spv::OpFwidthFine;
3250 break;
3251 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003252 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003253 unaryOp = spv::OpDPdxCoarse;
3254 break;
3255 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003256 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003257 unaryOp = spv::OpDPdyCoarse;
3258 break;
3259 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003260 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003261 unaryOp = spv::OpFwidthCoarse;
3262 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003263 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003264 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003265 libCall = spv::GLSLstd450InterpolateAtCentroid;
3266 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003267 case glslang::EOpAny:
3268 unaryOp = spv::OpAny;
3269 break;
3270 case glslang::EOpAll:
3271 unaryOp = spv::OpAll;
3272 break;
3273
3274 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003275 if (isFloat)
3276 libCall = spv::GLSLstd450FAbs;
3277 else
3278 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 break;
3280 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003281 if (isFloat)
3282 libCall = spv::GLSLstd450FSign;
3283 else
3284 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003285 break;
3286
John Kessenichfc51d282015-08-19 13:34:18 -06003287 case glslang::EOpAtomicCounterIncrement:
3288 case glslang::EOpAtomicCounterDecrement:
3289 case glslang::EOpAtomicCounter:
3290 {
3291 // Handle all of the atomics in one place, in createAtomicOperation()
3292 std::vector<spv::Id> operands;
3293 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003294 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003295 }
3296
John Kessenichfc51d282015-08-19 13:34:18 -06003297 case glslang::EOpBitFieldReverse:
3298 unaryOp = spv::OpBitReverse;
3299 break;
3300 case glslang::EOpBitCount:
3301 unaryOp = spv::OpBitCount;
3302 break;
3303 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003304 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003305 break;
3306 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003307 if (isUnsigned)
3308 libCall = spv::GLSLstd450FindUMsb;
3309 else
3310 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003311 break;
3312
Rex Xu574ab042016-04-14 16:53:07 +08003313 case glslang::EOpBallot:
3314 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003315 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003316 libCall = spv::GLSLstd450Bad;
3317 break;
3318
Rex Xu338b1852016-05-05 20:38:33 +08003319 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003320 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003321 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003322 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003323
John Kessenich140f3df2015-06-26 16:58:36 -06003324 default:
3325 return 0;
3326 }
3327
3328 spv::Id id;
3329 if (libCall >= 0) {
3330 std::vector<spv::Id> args;
3331 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003332 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003333 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003334 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003335 }
John Kessenich140f3df2015-06-26 16:58:36 -06003336
qining25262b32016-05-06 17:25:16 -04003337 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003338 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003339}
3340
John Kessenich7a53f762016-01-20 11:19:27 -07003341// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003342spv::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 -07003343{
3344 // Handle unary operations vector by vector.
3345 // The result type is the same type as the original type.
3346 // The algorithm is to:
3347 // - break the matrix into vectors
3348 // - apply the operation to each vector
3349 // - make a matrix out the vector results
3350
3351 // get the types sorted out
3352 int numCols = builder.getNumColumns(operand);
3353 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003354 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3355 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003356 std::vector<spv::Id> results;
3357
3358 // do each vector op
3359 for (int c = 0; c < numCols; ++c) {
3360 std::vector<unsigned int> indexes;
3361 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003362 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3363 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3364 addDecoration(destVec, noContraction);
3365 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003366 }
3367
3368 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003369 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003370}
3371
Rex Xu73e3ce72016-04-27 18:48:17 +08003372spv::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 -06003373{
3374 spv::Op convOp = spv::OpNop;
3375 spv::Id zero = 0;
3376 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003377 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003378
3379 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3380
3381 switch (op) {
3382 case glslang::EOpConvIntToBool:
3383 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003384 case glslang::EOpConvInt64ToBool:
3385 case glslang::EOpConvUint64ToBool:
3386 zero = (op == glslang::EOpConvInt64ToBool ||
3387 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003388 zero = makeSmearedConstant(zero, vectorSize);
3389 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3390
3391 case glslang::EOpConvFloatToBool:
3392 zero = builder.makeFloatConstant(0.0F);
3393 zero = makeSmearedConstant(zero, vectorSize);
3394 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3395
3396 case glslang::EOpConvDoubleToBool:
3397 zero = builder.makeDoubleConstant(0.0);
3398 zero = makeSmearedConstant(zero, vectorSize);
3399 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3400
3401 case glslang::EOpConvBoolToFloat:
3402 convOp = spv::OpSelect;
3403 zero = builder.makeFloatConstant(0.0);
3404 one = builder.makeFloatConstant(1.0);
3405 break;
3406 case glslang::EOpConvBoolToDouble:
3407 convOp = spv::OpSelect;
3408 zero = builder.makeDoubleConstant(0.0);
3409 one = builder.makeDoubleConstant(1.0);
3410 break;
3411 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003412 case glslang::EOpConvBoolToInt64:
3413 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3414 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003415 convOp = spv::OpSelect;
3416 break;
3417 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003418 case glslang::EOpConvBoolToUint64:
3419 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3420 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003421 convOp = spv::OpSelect;
3422 break;
3423
3424 case glslang::EOpConvIntToFloat:
3425 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003426 case glslang::EOpConvInt64ToFloat:
3427 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003428 convOp = spv::OpConvertSToF;
3429 break;
3430
3431 case glslang::EOpConvUintToFloat:
3432 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003433 case glslang::EOpConvUint64ToFloat:
3434 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003435 convOp = spv::OpConvertUToF;
3436 break;
3437
3438 case glslang::EOpConvDoubleToFloat:
3439 case glslang::EOpConvFloatToDouble:
3440 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003441 if (builder.isMatrixType(destType))
3442 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003443 break;
3444
3445 case glslang::EOpConvFloatToInt:
3446 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003447 case glslang::EOpConvFloatToInt64:
3448 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003449 convOp = spv::OpConvertFToS;
3450 break;
3451
3452 case glslang::EOpConvUintToInt:
3453 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003454 case glslang::EOpConvUint64ToInt64:
3455 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003456 if (builder.isInSpecConstCodeGenMode()) {
3457 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003458 zero = (op == glslang::EOpConvUintToInt64 ||
3459 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003460 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003461 // Use OpIAdd, instead of OpBitcast to do the conversion when
3462 // generating for OpSpecConstantOp instruction.
3463 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3464 }
3465 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003466 convOp = spv::OpBitcast;
3467 break;
3468
3469 case glslang::EOpConvFloatToUint:
3470 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003471 case glslang::EOpConvFloatToUint64:
3472 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003473 convOp = spv::OpConvertFToU;
3474 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003475
3476 case glslang::EOpConvIntToInt64:
3477 case glslang::EOpConvInt64ToInt:
3478 convOp = spv::OpSConvert;
3479 break;
3480
3481 case glslang::EOpConvUintToUint64:
3482 case glslang::EOpConvUint64ToUint:
3483 convOp = spv::OpUConvert;
3484 break;
3485
3486 case glslang::EOpConvIntToUint64:
3487 case glslang::EOpConvInt64ToUint:
3488 case glslang::EOpConvUint64ToInt:
3489 case glslang::EOpConvUintToInt64:
3490 // OpSConvert/OpUConvert + OpBitCast
3491 switch (op) {
3492 case glslang::EOpConvIntToUint64:
3493 convOp = spv::OpSConvert;
3494 type = builder.makeIntType(64);
3495 break;
3496 case glslang::EOpConvInt64ToUint:
3497 convOp = spv::OpSConvert;
3498 type = builder.makeIntType(32);
3499 break;
3500 case glslang::EOpConvUint64ToInt:
3501 convOp = spv::OpUConvert;
3502 type = builder.makeUintType(32);
3503 break;
3504 case glslang::EOpConvUintToInt64:
3505 convOp = spv::OpUConvert;
3506 type = builder.makeUintType(64);
3507 break;
3508 default:
3509 assert(0);
3510 break;
3511 }
3512
3513 if (vectorSize > 0)
3514 type = builder.makeVectorType(type, vectorSize);
3515
3516 operand = builder.createUnaryOp(convOp, type, operand);
3517
3518 if (builder.isInSpecConstCodeGenMode()) {
3519 // Build zero scalar or vector for OpIAdd.
3520 zero = (op == glslang::EOpConvIntToUint64 ||
3521 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3522 zero = makeSmearedConstant(zero, vectorSize);
3523 // Use OpIAdd, instead of OpBitcast to do the conversion when
3524 // generating for OpSpecConstantOp instruction.
3525 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3526 }
3527 // For normal run-time conversion instruction, use OpBitcast.
3528 convOp = spv::OpBitcast;
3529 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003530 default:
3531 break;
3532 }
3533
3534 spv::Id result = 0;
3535 if (convOp == spv::OpNop)
3536 return result;
3537
3538 if (convOp == spv::OpSelect) {
3539 zero = makeSmearedConstant(zero, vectorSize);
3540 one = makeSmearedConstant(one, vectorSize);
3541 result = builder.createTriOp(convOp, destType, operand, one, zero);
3542 } else
3543 result = builder.createUnaryOp(convOp, destType, operand);
3544
John Kessenich32cfd492016-02-02 12:37:46 -07003545 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003546}
3547
3548spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3549{
3550 if (vectorSize == 0)
3551 return constant;
3552
3553 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3554 std::vector<spv::Id> components;
3555 for (int c = 0; c < vectorSize; ++c)
3556 components.push_back(constant);
3557 return builder.makeCompositeConstant(vectorTypeId, components);
3558}
3559
John Kessenich426394d2015-07-23 10:22:48 -06003560// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003561spv::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 -06003562{
3563 spv::Op opCode = spv::OpNop;
3564
3565 switch (op) {
3566 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003567 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003568 opCode = spv::OpAtomicIAdd;
3569 break;
3570 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003571 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003572 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003573 break;
3574 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003575 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003576 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003577 break;
3578 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003579 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003580 opCode = spv::OpAtomicAnd;
3581 break;
3582 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003583 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003584 opCode = spv::OpAtomicOr;
3585 break;
3586 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003587 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003588 opCode = spv::OpAtomicXor;
3589 break;
3590 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003591 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003592 opCode = spv::OpAtomicExchange;
3593 break;
3594 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003595 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003596 opCode = spv::OpAtomicCompareExchange;
3597 break;
3598 case glslang::EOpAtomicCounterIncrement:
3599 opCode = spv::OpAtomicIIncrement;
3600 break;
3601 case glslang::EOpAtomicCounterDecrement:
3602 opCode = spv::OpAtomicIDecrement;
3603 break;
3604 case glslang::EOpAtomicCounter:
3605 opCode = spv::OpAtomicLoad;
3606 break;
3607 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003608 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003609 break;
3610 }
3611
3612 // Sort out the operands
3613 // - mapping from glslang -> SPV
3614 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003615 // - compare-exchange swaps the value and comparator
3616 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003617 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3618 auto opIt = operands.begin(); // walk the glslang operands
3619 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003620 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3621 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3622 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003623 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3624 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003625 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003626 spvAtomicOperands.push_back(*(opIt + 1));
3627 spvAtomicOperands.push_back(*opIt);
3628 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003629 }
John Kessenich426394d2015-07-23 10:22:48 -06003630
John Kessenich3e60a6f2015-09-14 22:45:16 -06003631 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003632 for (; opIt != operands.end(); ++opIt)
3633 spvAtomicOperands.push_back(*opIt);
3634
3635 return builder.createOp(opCode, typeId, spvAtomicOperands);
3636}
3637
John Kessenich91cef522016-05-05 16:45:40 -06003638// Create group invocation operations.
3639spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3640{
3641 builder.addCapability(spv::CapabilityGroups);
3642
3643 std::vector<spv::Id> operands;
3644 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3645 operands.push_back(operand);
3646
3647 switch (op) {
3648 case glslang::EOpAnyInvocation:
3649 case glslang::EOpAllInvocations:
3650 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3651
3652 case glslang::EOpAllInvocationsEqual:
3653 {
3654 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3655 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3656
3657 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3658 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3659 }
3660 default:
3661 logger->missingFunctionality("invocation operation");
3662 return spv::NoResult;
3663 }
3664}
3665
John Kessenich5e4b1242015-08-06 22:53:06 -06003666spv::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 -06003667{
Rex Xu8ff43de2016-04-22 16:51:45 +08003668 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003669 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3670
John Kessenich140f3df2015-06-26 16:58:36 -06003671 spv::Op opCode = spv::OpNop;
3672 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003673 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003674 spv::Id typeId0 = 0;
3675 if (consumedOperands > 0)
3676 typeId0 = builder.getTypeId(operands[0]);
3677 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003678
3679 switch (op) {
3680 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003681 if (isFloat)
3682 libCall = spv::GLSLstd450FMin;
3683 else if (isUnsigned)
3684 libCall = spv::GLSLstd450UMin;
3685 else
3686 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003687 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
3689 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003691 break;
3692 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 if (isFloat)
3694 libCall = spv::GLSLstd450FMax;
3695 else if (isUnsigned)
3696 libCall = spv::GLSLstd450UMax;
3697 else
3698 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003699 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpDot:
3705 opCode = spv::OpDot;
3706 break;
3707 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710
3711 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 if (isFloat)
3713 libCall = spv::GLSLstd450FClamp;
3714 else if (isUnsigned)
3715 libCall = spv::GLSLstd450UClamp;
3716 else
3717 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003718 builder.promoteScalar(precision, operands.front(), operands[1]);
3719 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003722 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3723 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003724 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003725 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003726 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003727 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003728 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003729 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003730 break;
3731 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003732 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003733 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003736 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003737 builder.promoteScalar(precision, operands[0], operands[2]);
3738 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003739 break;
3740
3741 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003742 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
3744 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003756 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003757 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003758 libCall = spv::GLSLstd450InterpolateAtSample;
3759 break;
3760 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003761 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003762 libCall = spv::GLSLstd450InterpolateAtOffset;
3763 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003764 case glslang::EOpAddCarry:
3765 opCode = spv::OpIAddCarry;
3766 typeId = builder.makeStructResultType(typeId0, typeId0);
3767 consumedOperands = 2;
3768 break;
3769 case glslang::EOpSubBorrow:
3770 opCode = spv::OpISubBorrow;
3771 typeId = builder.makeStructResultType(typeId0, typeId0);
3772 consumedOperands = 2;
3773 break;
3774 case glslang::EOpUMulExtended:
3775 opCode = spv::OpUMulExtended;
3776 typeId = builder.makeStructResultType(typeId0, typeId0);
3777 consumedOperands = 2;
3778 break;
3779 case glslang::EOpIMulExtended:
3780 opCode = spv::OpSMulExtended;
3781 typeId = builder.makeStructResultType(typeId0, typeId0);
3782 consumedOperands = 2;
3783 break;
3784 case glslang::EOpBitfieldExtract:
3785 if (isUnsigned)
3786 opCode = spv::OpBitFieldUExtract;
3787 else
3788 opCode = spv::OpBitFieldSExtract;
3789 break;
3790 case glslang::EOpBitfieldInsert:
3791 opCode = spv::OpBitFieldInsert;
3792 break;
3793
3794 case glslang::EOpFma:
3795 libCall = spv::GLSLstd450Fma;
3796 break;
3797 case glslang::EOpFrexp:
3798 libCall = spv::GLSLstd450FrexpStruct;
3799 if (builder.getNumComponents(operands[0]) == 1)
3800 frexpIntType = builder.makeIntegerType(32, true);
3801 else
3802 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3803 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3804 consumedOperands = 1;
3805 break;
3806 case glslang::EOpLdexp:
3807 libCall = spv::GLSLstd450Ldexp;
3808 break;
3809
Rex Xu574ab042016-04-14 16:53:07 +08003810 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003811 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003812 libCall = spv::GLSLstd450Bad;
3813 break;
3814
John Kessenich140f3df2015-06-26 16:58:36 -06003815 default:
3816 return 0;
3817 }
3818
3819 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003820 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003821 // Use an extended instruction from the standard library.
3822 // Construct the call arguments, without modifying the original operands vector.
3823 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3824 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003825 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003826 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003827 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003828 case 0:
3829 // should all be handled by visitAggregate and createNoArgOperation
3830 assert(0);
3831 return 0;
3832 case 1:
3833 // should all be handled by createUnaryOperation
3834 assert(0);
3835 return 0;
3836 case 2:
3837 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3838 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003839 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003840 // anything 3 or over doesn't have l-value operands, so all should be consumed
3841 assert(consumedOperands == operands.size());
3842 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003843 break;
3844 }
3845 }
3846
John Kessenich55e7d112015-11-15 21:33:39 -07003847 // Decode the return types that were structures
3848 switch (op) {
3849 case glslang::EOpAddCarry:
3850 case glslang::EOpSubBorrow:
3851 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3852 id = builder.createCompositeExtract(id, typeId0, 0);
3853 break;
3854 case glslang::EOpUMulExtended:
3855 case glslang::EOpIMulExtended:
3856 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3857 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3858 break;
3859 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003860 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003861 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3862 id = builder.createCompositeExtract(id, typeId0, 0);
3863 break;
3864 default:
3865 break;
3866 }
3867
John Kessenich32cfd492016-02-02 12:37:46 -07003868 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003869}
3870
3871// Intrinsics with no arguments, no return value, and no precision.
3872spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3873{
3874 // TODO: get the barrier operands correct
3875
3876 switch (op) {
3877 case glslang::EOpEmitVertex:
3878 builder.createNoResultOp(spv::OpEmitVertex);
3879 return 0;
3880 case glslang::EOpEndPrimitive:
3881 builder.createNoResultOp(spv::OpEndPrimitive);
3882 return 0;
3883 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003884 if (glslangIntermediate->getProfile() != EEsProfile)
3885 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003886 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003887 return 0;
3888 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003889 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003890 return 0;
3891 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003892 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003893 return 0;
3894 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003895 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 return 0;
3897 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003898 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003899 return 0;
3900 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003901 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003902 return 0;
3903 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003904 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003905 return 0;
3906 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003907 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003908 return 0;
3909 }
3910}
3911
3912spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3913{
John Kessenich2f273362015-07-18 22:34:27 -06003914 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003915 spv::Id id;
3916 if (symbolValues.end() != iter) {
3917 id = iter->second;
3918 return id;
3919 }
3920
3921 // it was not found, create it
3922 id = createSpvVariable(symbol);
3923 symbolValues[symbol->getId()] = id;
3924
3925 if (! symbol->getType().isStruct()) {
3926 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003927 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003928 if (symbol->getType().getQualifier().hasSpecConstantId())
3929 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003930 if (symbol->getQualifier().hasIndex())
3931 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3932 if (symbol->getQualifier().hasComponent())
3933 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3934 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003935 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003936 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003937 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003938 if (symbol->getQualifier().hasXfbBuffer())
3939 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3940 if (symbol->getQualifier().hasXfbOffset())
3941 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3942 }
3943 }
3944
scygan2c864272016-05-18 18:09:17 +02003945 if (symbol->getQualifier().hasLocation())
3946 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003947 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003948 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003949 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003950 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003951 }
John Kessenich140f3df2015-06-26 16:58:36 -06003952 if (symbol->getQualifier().hasSet())
3953 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003954 else if (IsDescriptorResource(symbol->getType())) {
3955 // default to 0
3956 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3957 }
John Kessenich140f3df2015-06-26 16:58:36 -06003958 if (symbol->getQualifier().hasBinding())
3959 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003960 if (symbol->getQualifier().hasAttachment())
3961 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003962 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003963 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003964 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003965 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003966 if (symbol->getQualifier().hasXfbBuffer())
3967 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3968 }
3969
Rex Xu1da878f2016-02-21 20:59:01 +08003970 if (symbol->getType().isImage()) {
3971 std::vector<spv::Decoration> memory;
3972 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3973 for (unsigned int i = 0; i < memory.size(); ++i)
3974 addDecoration(id, memory[i]);
3975 }
3976
John Kessenich140f3df2015-06-26 16:58:36 -06003977 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003978 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003980 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003981
John Kessenich140f3df2015-06-26 16:58:36 -06003982 return id;
3983}
3984
John Kessenich55e7d112015-11-15 21:33:39 -07003985// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003986void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3987{
3988 if (dec != spv::BadValue)
3989 builder.addDecoration(id, dec);
3990}
3991
John Kessenich55e7d112015-11-15 21:33:39 -07003992// If 'dec' is valid, add a one-operand decoration to an object
3993void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3994{
3995 if (dec != spv::BadValue)
3996 builder.addDecoration(id, dec, value);
3997}
3998
3999// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004000void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4001{
4002 if (dec != spv::BadValue)
4003 builder.addMemberDecoration(id, (unsigned)member, dec);
4004}
4005
John Kessenich92187592016-02-01 13:45:25 -07004006// If 'dec' is valid, add a one-operand decoration to a struct member
4007void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4008{
4009 if (dec != spv::BadValue)
4010 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4011}
4012
John Kessenich55e7d112015-11-15 21:33:39 -07004013// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004014// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004015//
4016// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4017//
4018// Recursively walk the nodes. The nodes form a tree whose leaves are
4019// regular constants, which themselves are trees that createSpvConstant()
4020// recursively walks. So, this function walks the "top" of the tree:
4021// - emit specialization constant-building instructions for specConstant
4022// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004023spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004024{
John Kessenich7cc0e282016-03-20 00:46:02 -06004025 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004026
qining4f4bb812016-04-03 23:55:17 -04004027 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004028 if (! node.getQualifier().specConstant) {
4029 // hand off to the non-spec-constant path
4030 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4031 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004032 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004033 nextConst, false);
4034 }
4035
4036 // We now know we have a specialization constant to build
4037
qining4f4bb812016-04-03 23:55:17 -04004038 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
4039 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4040 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4041 std::vector<spv::Id> dimConstId;
4042 for (int dim = 0; dim < 3; ++dim) {
4043 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4044 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4045 if (specConst)
4046 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4047 }
4048 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4049 }
4050
4051 // An AST node labelled as specialization constant should be a symbol node.
4052 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4053 if (auto* sn = node.getAsSymbolNode()) {
4054 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004055 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4056 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4057 // will set the builder into spec constant op instruction generating mode.
4058 sub_tree->traverse(this);
4059 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004060 } else if (auto* const_union_array = &sn->getConstArray()){
4061 int nextConst = 0;
4062 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004063 }
4064 }
qining4f4bb812016-04-03 23:55:17 -04004065
4066 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4067 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004068 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004069 exit(1);
4070 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004071}
4072
John Kessenich140f3df2015-06-26 16:58:36 -06004073// Use 'consts' as the flattened glslang source of scalar constants to recursively
4074// build the aggregate SPIR-V constant.
4075//
4076// If there are not enough elements present in 'consts', 0 will be substituted;
4077// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4078//
qining08408382016-03-21 09:51:37 -04004079spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004080{
4081 // vector of constants for SPIR-V
4082 std::vector<spv::Id> spvConsts;
4083
4084 // Type is used for struct and array constants
4085 spv::Id typeId = convertGlslangToSpvType(glslangType);
4086
4087 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004088 glslang::TType elementType(glslangType, 0);
4089 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004090 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004091 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004092 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004093 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004094 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004095 } else if (glslangType.getStruct()) {
4096 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4097 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004098 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004099 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004100 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4101 bool zero = nextConst >= consts.size();
4102 switch (glslangType.getBasicType()) {
4103 case glslang::EbtInt:
4104 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4105 break;
4106 case glslang::EbtUint:
4107 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4108 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004109 case glslang::EbtInt64:
4110 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4111 break;
4112 case glslang::EbtUint64:
4113 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4114 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 case glslang::EbtFloat:
4116 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4117 break;
4118 case glslang::EbtDouble:
4119 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4120 break;
4121 case glslang::EbtBool:
4122 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4123 break;
4124 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004125 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004126 break;
4127 }
4128 ++nextConst;
4129 }
4130 } else {
4131 // we have a non-aggregate (scalar) constant
4132 bool zero = nextConst >= consts.size();
4133 spv::Id scalar = 0;
4134 switch (glslangType.getBasicType()) {
4135 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004136 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004137 break;
4138 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004139 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004141 case glslang::EbtInt64:
4142 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4143 break;
4144 case glslang::EbtUint64:
4145 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004147 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004148 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004151 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004154 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004155 break;
4156 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004157 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004158 break;
4159 }
4160 ++nextConst;
4161 return scalar;
4162 }
4163
4164 return builder.makeCompositeConstant(typeId, spvConsts);
4165}
4166
John Kessenich7c1aa102015-10-15 13:29:11 -06004167// Return true if the node is a constant or symbol whose reading has no
4168// non-trivial observable cost or effect.
4169bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4170{
4171 // don't know what this is
4172 if (node == nullptr)
4173 return false;
4174
4175 // a constant is safe
4176 if (node->getAsConstantUnion() != nullptr)
4177 return true;
4178
4179 // not a symbol means non-trivial
4180 if (node->getAsSymbolNode() == nullptr)
4181 return false;
4182
4183 // a symbol, depends on what's being read
4184 switch (node->getType().getQualifier().storage) {
4185 case glslang::EvqTemporary:
4186 case glslang::EvqGlobal:
4187 case glslang::EvqIn:
4188 case glslang::EvqInOut:
4189 case glslang::EvqConst:
4190 case glslang::EvqConstReadOnly:
4191 case glslang::EvqUniform:
4192 return true;
4193 default:
4194 return false;
4195 }
qining25262b32016-05-06 17:25:16 -04004196}
John Kessenich7c1aa102015-10-15 13:29:11 -06004197
4198// A node is trivial if it is a single operation with no side effects.
4199// Error on the side of saying non-trivial.
4200// Return true if trivial.
4201bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4202{
4203 if (node == nullptr)
4204 return false;
4205
4206 // symbols and constants are trivial
4207 if (isTrivialLeaf(node))
4208 return true;
4209
4210 // otherwise, it needs to be a simple operation or one or two leaf nodes
4211
4212 // not a simple operation
4213 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4214 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4215 if (binaryNode == nullptr && unaryNode == nullptr)
4216 return false;
4217
4218 // not on leaf nodes
4219 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4220 return false;
4221
4222 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4223 return false;
4224 }
4225
4226 switch (node->getAsOperator()->getOp()) {
4227 case glslang::EOpLogicalNot:
4228 case glslang::EOpConvIntToBool:
4229 case glslang::EOpConvUintToBool:
4230 case glslang::EOpConvFloatToBool:
4231 case glslang::EOpConvDoubleToBool:
4232 case glslang::EOpEqual:
4233 case glslang::EOpNotEqual:
4234 case glslang::EOpLessThan:
4235 case glslang::EOpGreaterThan:
4236 case glslang::EOpLessThanEqual:
4237 case glslang::EOpGreaterThanEqual:
4238 case glslang::EOpIndexDirect:
4239 case glslang::EOpIndexDirectStruct:
4240 case glslang::EOpLogicalXor:
4241 case glslang::EOpAny:
4242 case glslang::EOpAll:
4243 return true;
4244 default:
4245 return false;
4246 }
4247}
4248
4249// Emit short-circuiting code, where 'right' is never evaluated unless
4250// the left side is true (for &&) or false (for ||).
4251spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4252{
4253 spv::Id boolTypeId = builder.makeBoolType();
4254
4255 // emit left operand
4256 builder.clearAccessChain();
4257 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004258 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004259
4260 // Operands to accumulate OpPhi operands
4261 std::vector<spv::Id> phiOperands;
4262 // accumulate left operand's phi information
4263 phiOperands.push_back(leftId);
4264 phiOperands.push_back(builder.getBuildPoint()->getId());
4265
4266 // Make the two kinds of operation symmetric with a "!"
4267 // || => emit "if (! left) result = right"
4268 // && => emit "if ( left) result = right"
4269 //
4270 // TODO: this runtime "not" for || could be avoided by adding functionality
4271 // to 'builder' to have an "else" without an "then"
4272 if (op == glslang::EOpLogicalOr)
4273 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4274
4275 // make an "if" based on the left value
4276 spv::Builder::If ifBuilder(leftId, builder);
4277
4278 // emit right operand as the "then" part of the "if"
4279 builder.clearAccessChain();
4280 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004281 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004282
4283 // accumulate left operand's phi information
4284 phiOperands.push_back(rightId);
4285 phiOperands.push_back(builder.getBuildPoint()->getId());
4286
4287 // finish the "if"
4288 ifBuilder.makeEndIf();
4289
4290 // phi together the two results
4291 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4292}
4293
John Kessenich140f3df2015-06-26 16:58:36 -06004294}; // end anonymous namespace
4295
4296namespace glslang {
4297
John Kessenich68d78fd2015-07-12 19:28:10 -06004298void GetSpirvVersion(std::string& version)
4299{
John Kessenich9e55f632015-07-15 10:03:39 -06004300 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004301 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004302 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004303 version = buf;
4304}
4305
John Kessenich140f3df2015-06-26 16:58:36 -06004306// Write SPIR-V out to a binary file
4307void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4308{
4309 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004310 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004311 for (int i = 0; i < (int)spirv.size(); ++i) {
4312 unsigned int word = spirv[i];
4313 out.write((const char*)&word, 4);
4314 }
4315 out.close();
4316}
4317
4318//
4319// Set up the glslang traversal
4320//
4321void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4322{
Lei Zhang17535f72016-05-04 15:55:59 -04004323 spv::SpvBuildLogger logger;
4324 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004325}
4326
Lei Zhang17535f72016-05-04 15:55:59 -04004327void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004328{
John Kessenich140f3df2015-06-26 16:58:36 -06004329 TIntermNode* root = intermediate.getTreeRoot();
4330
4331 if (root == 0)
4332 return;
4333
4334 glslang::GetThreadPoolAllocator().push();
4335
Lei Zhang17535f72016-05-04 15:55:59 -04004336 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004337
4338 root->traverse(&it);
4339
4340 it.dumpSpv(spirv);
4341
4342 glslang::GetThreadPoolAllocator().pop();
4343}
4344
4345}; // end namespace glslang