blob: d6ae94157b71e9b2aab3f1ab4c235437d5fd567c [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:
Rex Xubbceed72016-05-21 09:40:44 +0800111 spv::Decoration TranslateAuxiliaryStorageDecoration(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.
Rex Xubbceed72016-05-21 09:40:44 +0800357spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600358{
Rex Xubbceed72016-05-21 09:40:44 +0800359 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;
Rex Xubbceed72016-05-21 09:40:44 +0800362 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700363 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700364 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600365 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else
367 return (spv::Decoration)spv::BadValue;
368}
369
370// Translate glslang type to SPIR-V auxiliary storage decorations.
371// Returns spv::Decoration(spv::BadValue) when no decoration
372// should be applied.
373spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
374{
375 if (qualifier.patch)
376 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700377 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600378 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700379 else if (qualifier.sample) {
380 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700382 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600383 return (spv::Decoration)spv::BadValue;
384}
385
John Kessenich92187592016-02-01 13:45:25 -0700386// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600388{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700389 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600390 return spv::DecorationInvariant;
391 else
392 return (spv::Decoration)spv::BadValue;
393}
394
qining9220dbb2016-05-04 17:34:38 -0400395// If glslang type is noContraction, return SPIR-V NoContraction decoration.
396spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
397{
398 if (qualifier.noContraction)
399 return spv::DecorationNoContraction;
400 else
401 return (spv::Decoration)spv::BadValue;
402}
403
John Kessenich140f3df2015-06-26 16:58:36 -0600404// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenichebb50532016-05-16 19:22:05 -0600405spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool member)
John Kessenich140f3df2015-06-26 16:58:36 -0600406{
407 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700408 case glslang::EbvPointSize:
409 switch (glslangIntermediate->getStage()) {
410 case EShLangGeometry:
411 builder.addCapability(spv::CapabilityGeometryPointSize);
412 break;
413 case EShLangTessControl:
414 case EShLangTessEvaluation:
415 builder.addCapability(spv::CapabilityTessellationPointSize);
416 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100417 default:
418 break;
John Kessenich92187592016-02-01 13:45:25 -0700419 }
420 return spv::BuiltInPointSize;
421
John Kessenichebb50532016-05-16 19:22:05 -0600422 // These *Distance capabilities logically belong here, but if the member is declared and
423 // then never used, consumers of SPIR-V prefer the capability not be declared.
424 // They are now generated when used, rather than here when declared.
425 // Potentially, the specification should be more clear what the minimum
426 // use needed is to trigger the capability.
427 //
John Kessenich92187592016-02-01 13:45:25 -0700428 case glslang::EbvClipDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600429 if (! member)
430 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700431 return spv::BuiltInClipDistance;
432
433 case glslang::EbvCullDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600434 if (! member)
435 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700436 return spv::BuiltInCullDistance;
437
438 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500439 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700440 return spv::BuiltInViewportIndex;
441
John Kessenich5e801132016-02-15 11:09:46 -0700442 case glslang::EbvSampleId:
443 builder.addCapability(spv::CapabilitySampleRateShading);
444 return spv::BuiltInSampleId;
445
446 case glslang::EbvSamplePosition:
447 builder.addCapability(spv::CapabilitySampleRateShading);
448 return spv::BuiltInSamplePosition;
449
450 case glslang::EbvSampleMask:
451 builder.addCapability(spv::CapabilitySampleRateShading);
452 return spv::BuiltInSampleMask;
453
John Kessenich140f3df2015-06-26 16:58:36 -0600454 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600455 case glslang::EbvVertexId: return spv::BuiltInVertexId;
456 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700457 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
458 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600459 case glslang::EbvBaseVertex:
460 case glslang::EbvBaseInstance:
461 case glslang::EbvDrawId:
462 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600463 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600464 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
466 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
467 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600468 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
469 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
470 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
471 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
472 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
473 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
474 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600475 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
476 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
477 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
478 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
479 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
480 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
481 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
482 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800483 case glslang::EbvSubGroupSize:
484 case glslang::EbvSubGroupInvocation:
485 case glslang::EbvSubGroupEqMask:
486 case glslang::EbvSubGroupGeMask:
487 case glslang::EbvSubGroupGtMask:
488 case glslang::EbvSubGroupLeMask:
489 case glslang::EbvSubGroupLtMask:
490 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600491 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800492 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600493 default: return (spv::BuiltIn)spv::BadValue;
494 }
495}
496
Rex Xufc618912015-09-09 16:42:49 +0800497// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700498spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800499{
500 assert(type.getBasicType() == glslang::EbtSampler);
501
John Kessenich5d0fa972016-02-15 11:57:00 -0700502 // Check for capabilities
503 switch (type.getQualifier().layoutFormat) {
504 case glslang::ElfRg32f:
505 case glslang::ElfRg16f:
506 case glslang::ElfR11fG11fB10f:
507 case glslang::ElfR16f:
508 case glslang::ElfRgba16:
509 case glslang::ElfRgb10A2:
510 case glslang::ElfRg16:
511 case glslang::ElfRg8:
512 case glslang::ElfR16:
513 case glslang::ElfR8:
514 case glslang::ElfRgba16Snorm:
515 case glslang::ElfRg16Snorm:
516 case glslang::ElfRg8Snorm:
517 case glslang::ElfR16Snorm:
518 case glslang::ElfR8Snorm:
519
520 case glslang::ElfRg32i:
521 case glslang::ElfRg16i:
522 case glslang::ElfRg8i:
523 case glslang::ElfR16i:
524 case glslang::ElfR8i:
525
526 case glslang::ElfRgb10a2ui:
527 case glslang::ElfRg32ui:
528 case glslang::ElfRg16ui:
529 case glslang::ElfRg8ui:
530 case glslang::ElfR16ui:
531 case glslang::ElfR8ui:
532 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
533 break;
534
535 default:
536 break;
537 }
538
539 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800540 switch (type.getQualifier().layoutFormat) {
541 case glslang::ElfNone: return spv::ImageFormatUnknown;
542 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
543 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
544 case glslang::ElfR32f: return spv::ImageFormatR32f;
545 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
546 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
547 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
548 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
549 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
550 case glslang::ElfR16f: return spv::ImageFormatR16f;
551 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
552 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
553 case glslang::ElfRg16: return spv::ImageFormatRg16;
554 case glslang::ElfRg8: return spv::ImageFormatRg8;
555 case glslang::ElfR16: return spv::ImageFormatR16;
556 case glslang::ElfR8: return spv::ImageFormatR8;
557 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
558 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
559 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
560 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
561 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
562 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
563 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
564 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
565 case glslang::ElfR32i: return spv::ImageFormatR32i;
566 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
567 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
568 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
569 case glslang::ElfR16i: return spv::ImageFormatR16i;
570 case glslang::ElfR8i: return spv::ImageFormatR8i;
571 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
572 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
573 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
574 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
575 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
576 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
577 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
578 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
579 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
580 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
581 default: return (spv::ImageFormat)spv::BadValue;
582 }
583}
584
qining25262b32016-05-06 17:25:16 -0400585// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700586// descriptor set.
587bool IsDescriptorResource(const glslang::TType& type)
588{
John Kessenichf7497e22016-03-08 21:36:22 -0700589 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700590 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700591 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700592
593 // non block...
594 // basically samplerXXX/subpass/sampler/texture are all included
595 // if they are the global-scope-class, not the function parameter
596 // (or local, if they ever exist) class.
597 if (type.getBasicType() == glslang::EbtSampler)
598 return type.getQualifier().isUniformOrBuffer();
599
600 // None of the above.
601 return false;
602}
603
John Kesseniche0b6cad2015-12-24 10:30:13 -0700604void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
605{
606 if (child.layoutMatrix == glslang::ElmNone)
607 child.layoutMatrix = parent.layoutMatrix;
608
609 if (parent.invariant)
610 child.invariant = true;
611 if (parent.nopersp)
612 child.nopersp = true;
613 if (parent.flat)
614 child.flat = true;
615 if (parent.centroid)
616 child.centroid = true;
617 if (parent.patch)
618 child.patch = true;
619 if (parent.sample)
620 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800621 if (parent.coherent)
622 child.coherent = true;
623 if (parent.volatil)
624 child.volatil = true;
625 if (parent.restrict)
626 child.restrict = true;
627 if (parent.readonly)
628 child.readonly = true;
629 if (parent.writeonly)
630 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700631}
632
633bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
634{
John Kessenich7b9fa252016-01-21 18:56:57 -0700635 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700636 // - struct members can inherit from a struct declaration
637 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
638 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400639 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700640}
641
John Kessenich140f3df2015-06-26 16:58:36 -0600642//
643// Implement the TGlslangToSpvTraverser class.
644//
645
Lei Zhang17535f72016-05-04 15:55:59 -0400646TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
647 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
648 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600649 inMain(false), mainTerminated(false), linkageOnly(false),
650 glslangIntermediate(glslangIntermediate)
651{
652 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
653
654 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700655 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600656 stdBuiltins = builder.import("GLSL.std.450");
657 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700658 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
659 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600660
661 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600662 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
663 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600664 builder.addSourceExtension(it->c_str());
665
666 // Add the top-level modes for this shader.
667
John Kessenich92187592016-02-01 13:45:25 -0700668 if (glslangIntermediate->getXfbMode()) {
669 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600670 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700671 }
John Kessenich140f3df2015-06-26 16:58:36 -0600672
673 unsigned int mode;
674 switch (glslangIntermediate->getStage()) {
675 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600676 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600677 break;
678
679 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600680 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600681 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
682 break;
683
684 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600685 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600686 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700687 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
688 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
689 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600690 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600691 }
692 if (mode != spv::BadValue)
693 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
694
John Kesseniche6903322015-10-13 16:29:02 -0600695 switch (glslangIntermediate->getVertexSpacing()) {
696 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
697 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
698 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
699 default: mode = spv::BadValue; break;
700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703
704 switch (glslangIntermediate->getVertexOrder()) {
705 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
706 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
707 default: mode = spv::BadValue; break;
708 }
709 if (mode != spv::BadValue)
710 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
711
712 if (glslangIntermediate->getPointMode())
713 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600714 break;
715
716 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600717 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600718 switch (glslangIntermediate->getInputPrimitive()) {
719 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
720 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
721 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700722 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600723 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
724 default: mode = spv::BadValue; break;
725 }
726 if (mode != spv::BadValue)
727 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600728
John Kessenich140f3df2015-06-26 16:58:36 -0600729 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
730
731 switch (glslangIntermediate->getOutputPrimitive()) {
732 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
733 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
734 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
735 default: mode = spv::BadValue; break;
736 }
737 if (mode != spv::BadValue)
738 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
739 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
740 break;
741
742 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600743 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600744 if (glslangIntermediate->getPixelCenterInteger())
745 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600746
John Kessenich140f3df2015-06-26 16:58:36 -0600747 if (glslangIntermediate->getOriginUpperLeft())
748 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600749 else
750 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600751
752 if (glslangIntermediate->getEarlyFragmentTests())
753 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
754
755 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600756 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
757 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
758 default: mode = spv::BadValue; break;
759 }
760 if (mode != spv::BadValue)
761 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
762
763 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
764 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600765 break;
766
767 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600768 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600769 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
770 glslangIntermediate->getLocalSize(1),
771 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600772 break;
773
774 default:
775 break;
776 }
777
778}
779
John Kessenich7ba63412015-12-20 17:37:07 -0700780// Finish everything and dump
781void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
782{
783 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100784 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
785 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700786
qiningda397332016-03-09 19:54:03 -0500787 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700788 builder.dump(out);
789}
790
John Kessenich140f3df2015-06-26 16:58:36 -0600791TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
792{
793 if (! mainTerminated) {
794 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
795 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600796 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600797 }
798}
799
800//
801// Implement the traversal functions.
802//
803// Return true from interior nodes to have the external traversal
804// continue on to children. Return false if children were
805// already processed.
806//
807
808//
qining25262b32016-05-06 17:25:16 -0400809// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600810// - uniform/input reads
811// - output writes
812// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
813// - something simple that degenerates into the last bullet
814//
815void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
816{
qining75d1d802016-04-06 14:42:01 -0400817 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
818 if (symbol->getType().getQualifier().isSpecConstant())
819 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
820
John Kessenich140f3df2015-06-26 16:58:36 -0600821 // getSymbolId() will set up all the IO decorations on the first call.
822 // Formal function parameters were mapped during makeFunctions().
823 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700824
825 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
826 if (builder.isPointer(id)) {
827 spv::StorageClass sc = builder.getStorageClass(id);
828 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
829 iOSet.insert(id);
830 }
831
832 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700833 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600834 // Prepare to generate code for the access
835
836 // L-value chains will be computed left to right. We're on the symbol now,
837 // which is the left-most part of the access chain, so now is "clear" time,
838 // followed by setting the base.
839 builder.clearAccessChain();
840
841 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700842 // except for
843 // A) "const in" arguments to a function, which are an intermediate object.
844 // See comments in handleUserFunctionCall().
845 // B) Specialization constants (normal constant don't even come in as a variable),
846 // These are also pure R-values.
847 glslang::TQualifier qualifier = symbol->getQualifier();
848 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
849 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600850 builder.setAccessChainRValue(id);
851 else
852 builder.setAccessChainLValue(id);
853 }
854}
855
856bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
857{
qining40887662016-04-03 22:20:42 -0400858 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
859 if (node->getType().getQualifier().isSpecConstant())
860 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
861
John Kessenich140f3df2015-06-26 16:58:36 -0600862 // First, handle special cases
863 switch (node->getOp()) {
864 case glslang::EOpAssign:
865 case glslang::EOpAddAssign:
866 case glslang::EOpSubAssign:
867 case glslang::EOpMulAssign:
868 case glslang::EOpVectorTimesMatrixAssign:
869 case glslang::EOpVectorTimesScalarAssign:
870 case glslang::EOpMatrixTimesScalarAssign:
871 case glslang::EOpMatrixTimesMatrixAssign:
872 case glslang::EOpDivAssign:
873 case glslang::EOpModAssign:
874 case glslang::EOpAndAssign:
875 case glslang::EOpInclusiveOrAssign:
876 case glslang::EOpExclusiveOrAssign:
877 case glslang::EOpLeftShiftAssign:
878 case glslang::EOpRightShiftAssign:
879 // A bin-op assign "a += b" means the same thing as "a = a + b"
880 // where a is evaluated before b. For a simple assignment, GLSL
881 // says to evaluate the left before the right. So, always, left
882 // node then right node.
883 {
884 // get the left l-value, save it away
885 builder.clearAccessChain();
886 node->getLeft()->traverse(this);
887 spv::Builder::AccessChain lValue = builder.getAccessChain();
888
889 // evaluate the right
890 builder.clearAccessChain();
891 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700892 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 if (node->getOp() != glslang::EOpAssign) {
895 // the left is also an r-value
896 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700897 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600898
899 // do the operation
qining25262b32016-05-06 17:25:16 -0400900 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
901 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600902 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
903 node->getType().getBasicType());
904
905 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700906 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600907 }
908
909 // store the result
910 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800911 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600912
913 // assignments are expressions having an rValue after they are evaluated...
914 builder.clearAccessChain();
915 builder.setAccessChainRValue(rValue);
916 }
917 return false;
918 case glslang::EOpIndexDirect:
919 case glslang::EOpIndexDirectStruct:
920 {
921 // Get the left part of the access chain.
922 node->getLeft()->traverse(this);
923
924 // Add the next element in the chain
925
John Kessenich55e7d112015-11-15 21:33:39 -0700926 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600927 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
928 // This may be, e.g., an anonymous block-member selection, which generally need
929 // index remapping due to hidden members in anonymous blocks.
930 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700931 assert(remapper.size() > 0);
932 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600933 }
934
935 if (! node->getLeft()->getType().isArray() &&
936 node->getLeft()->getType().isVector() &&
937 node->getOp() == glslang::EOpIndexDirect) {
938 // This is essentially a hard-coded vector swizzle of size 1,
939 // so short circuit the access-chain stuff with a swizzle.
940 std::vector<unsigned> swizzle;
941 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600942 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600943 } else {
944 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600945 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenichebb50532016-05-16 19:22:05 -0600946
947 // Add capabilities here for accessing clip/cull distance
948 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
949 declareClipCullCapability(*node->getLeft()->getType().getStruct(), index);
John Kessenich140f3df2015-06-26 16:58:36 -0600950 }
951 }
952 return false;
953 case glslang::EOpIndexIndirect:
954 {
955 // Structure or array or vector indirection.
956 // Will use native SPIR-V access-chain for struct and array indirection;
957 // matrices are arrays of vectors, so will also work for a matrix.
958 // Will use the access chain's 'component' for variable index into a vector.
959
960 // This adapter is building access chains left to right.
961 // Set up the access chain to the left.
962 node->getLeft()->traverse(this);
963
964 // save it so that computing the right side doesn't trash it
965 spv::Builder::AccessChain partial = builder.getAccessChain();
966
967 // compute the next index in the chain
968 builder.clearAccessChain();
969 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700970 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600971
972 // restore the saved access chain
973 builder.setAccessChain(partial);
974
975 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600976 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600977 else
John Kessenichfa668da2015-09-13 14:46:30 -0600978 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600979 }
980 return false;
981 case glslang::EOpVectorSwizzle:
982 {
983 node->getLeft()->traverse(this);
984 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
985 std::vector<unsigned> swizzle;
986 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
987 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600988 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600989 }
990 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600991 case glslang::EOpLogicalOr:
992 case glslang::EOpLogicalAnd:
993 {
994
995 // These may require short circuiting, but can sometimes be done as straight
996 // binary operations. The right operand must be short circuited if it has
997 // side effects, and should probably be if it is complex.
998 if (isTrivial(node->getRight()->getAsTyped()))
999 break; // handle below as a normal binary operation
1000 // otherwise, we need to do dynamic short circuiting on the right operand
1001 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1002 builder.clearAccessChain();
1003 builder.setAccessChainRValue(result);
1004 }
1005 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001006 default:
1007 break;
1008 }
1009
1010 // Assume generic binary op...
1011
John Kessenich32cfd492016-02-02 12:37:46 -07001012 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001013 builder.clearAccessChain();
1014 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001015 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001016
John Kessenich32cfd492016-02-02 12:37:46 -07001017 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001018 builder.clearAccessChain();
1019 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001020 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001021
John Kessenich32cfd492016-02-02 12:37:46 -07001022 // get result
1023 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001024 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001025 convertGlslangToSpvType(node->getType()), left, right,
1026 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001027
John Kessenich50e57562015-12-21 21:21:11 -07001028 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001029 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001030 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001031 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001032 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001033 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001034 return false;
1035 }
John Kessenich140f3df2015-06-26 16:58:36 -06001036}
1037
1038bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1039{
qining40887662016-04-03 22:20:42 -04001040 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1041 if (node->getType().getQualifier().isSpecConstant())
1042 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1043
John Kessenichfc51d282015-08-19 13:34:18 -06001044 spv::Id result = spv::NoResult;
1045
1046 // try texturing first
1047 result = createImageTextureFunctionCall(node);
1048 if (result != spv::NoResult) {
1049 builder.clearAccessChain();
1050 builder.setAccessChainRValue(result);
1051
1052 return false; // done with this node
1053 }
1054
1055 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001056
1057 if (node->getOp() == glslang::EOpArrayLength) {
1058 // Quite special; won't want to evaluate the operand.
1059
1060 // Normal .length() would have been constant folded by the front-end.
1061 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001062 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001063 assert(node->getOperand()->getType().isRuntimeSizedArray());
1064 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1065 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001066 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1067 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001068
1069 builder.clearAccessChain();
1070 builder.setAccessChainRValue(length);
1071
1072 return false;
1073 }
1074
John Kessenichfc51d282015-08-19 13:34:18 -06001075 // Start by evaluating the operand
1076
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.clearAccessChain();
1078 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001079
Rex Xufc618912015-09-09 16:42:49 +08001080 spv::Id operand = spv::NoResult;
1081
1082 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1083 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001084 node->getOp() == glslang::EOpAtomicCounter ||
1085 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001086 operand = builder.accessChainGetLValue(); // Special case l-value operands
1087 else
John Kessenich32cfd492016-02-02 12:37:46 -07001088 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001089
1090 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001091 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001092
1093 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001094 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001095 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001096
1097 // if not, then possibly an operation
1098 if (! result)
qining25262b32016-05-06 17:25:16 -04001099 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
1101 if (result) {
1102 builder.clearAccessChain();
1103 builder.setAccessChainRValue(result);
1104
1105 return false; // done with this node
1106 }
1107
1108 // it must be a special case, check...
1109 switch (node->getOp()) {
1110 case glslang::EOpPostIncrement:
1111 case glslang::EOpPostDecrement:
1112 case glslang::EOpPreIncrement:
1113 case glslang::EOpPreDecrement:
1114 {
1115 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001116 spv::Id one = 0;
1117 if (node->getBasicType() == glslang::EbtFloat)
1118 one = builder.makeFloatConstant(1.0F);
1119 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1120 one = builder.makeInt64Constant(1);
1121 else
1122 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001123 glslang::TOperator op;
1124 if (node->getOp() == glslang::EOpPreIncrement ||
1125 node->getOp() == glslang::EOpPostIncrement)
1126 op = glslang::EOpAdd;
1127 else
1128 op = glslang::EOpSub;
1129
qining25262b32016-05-06 17:25:16 -04001130 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1131 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001132 convertGlslangToSpvType(node->getType()), operand, one,
1133 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001134 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001135
1136 // The result of operation is always stored, but conditionally the
1137 // consumed result. The consumed result is always an r-value.
1138 builder.accessChainStore(result);
1139 builder.clearAccessChain();
1140 if (node->getOp() == glslang::EOpPreIncrement ||
1141 node->getOp() == glslang::EOpPreDecrement)
1142 builder.setAccessChainRValue(result);
1143 else
1144 builder.setAccessChainRValue(operand);
1145 }
1146
1147 return false;
1148
1149 case glslang::EOpEmitStreamVertex:
1150 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1151 return false;
1152 case glslang::EOpEndStreamPrimitive:
1153 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1154 return false;
1155
1156 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001157 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001158 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001159 }
John Kessenich140f3df2015-06-26 16:58:36 -06001160}
1161
1162bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1163{
qining27e04a02016-04-14 16:40:20 -04001164 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1165 if (node->getType().getQualifier().isSpecConstant())
1166 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1167
John Kessenichfc51d282015-08-19 13:34:18 -06001168 spv::Id result = spv::NoResult;
1169
1170 // try texturing
1171 result = createImageTextureFunctionCall(node);
1172 if (result != spv::NoResult) {
1173 builder.clearAccessChain();
1174 builder.setAccessChainRValue(result);
1175
1176 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001177 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001178 // "imageStore" is a special case, which has no result
1179 return false;
1180 }
John Kessenichfc51d282015-08-19 13:34:18 -06001181
John Kessenich140f3df2015-06-26 16:58:36 -06001182 glslang::TOperator binOp = glslang::EOpNull;
1183 bool reduceComparison = true;
1184 bool isMatrix = false;
1185 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001186 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001187
1188 assert(node->getOp());
1189
1190 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1191
1192 switch (node->getOp()) {
1193 case glslang::EOpSequence:
1194 {
1195 if (preVisit)
1196 ++sequenceDepth;
1197 else
1198 --sequenceDepth;
1199
1200 if (sequenceDepth == 1) {
1201 // If this is the parent node of all the functions, we want to see them
1202 // early, so all call points have actual SPIR-V functions to reference.
1203 // In all cases, still let the traverser visit the children for us.
1204 makeFunctions(node->getAsAggregate()->getSequence());
1205
1206 // Also, we want all globals initializers to go into the entry of main(), before
1207 // anything else gets there, so visit out of order, doing them all now.
1208 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1209
1210 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1211 // so do them manually.
1212 visitFunctions(node->getAsAggregate()->getSequence());
1213
1214 return false;
1215 }
1216
1217 return true;
1218 }
1219 case glslang::EOpLinkerObjects:
1220 {
1221 if (visit == glslang::EvPreVisit)
1222 linkageOnly = true;
1223 else
1224 linkageOnly = false;
1225
1226 return true;
1227 }
1228 case glslang::EOpComma:
1229 {
1230 // processing from left to right naturally leaves the right-most
1231 // lying around in the access chain
1232 glslang::TIntermSequence& glslangOperands = node->getSequence();
1233 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1234 glslangOperands[i]->traverse(this);
1235
1236 return false;
1237 }
1238 case glslang::EOpFunction:
1239 if (visit == glslang::EvPreVisit) {
1240 if (isShaderEntrypoint(node)) {
1241 inMain = true;
1242 builder.setBuildPoint(shaderEntry->getLastBlock());
1243 } else {
1244 handleFunctionEntry(node);
1245 }
1246 } else {
1247 if (inMain)
1248 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001249 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001250 inMain = false;
1251 }
1252
1253 return true;
1254 case glslang::EOpParameters:
1255 // Parameters will have been consumed by EOpFunction processing, but not
1256 // the body, so we still visited the function node's children, making this
1257 // child redundant.
1258 return false;
1259 case glslang::EOpFunctionCall:
1260 {
1261 if (node->isUserDefined())
1262 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001263 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1264 if (result) {
1265 builder.clearAccessChain();
1266 builder.setAccessChainRValue(result);
1267 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001268 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001269
1270 return false;
1271 }
1272 case glslang::EOpConstructMat2x2:
1273 case glslang::EOpConstructMat2x3:
1274 case glslang::EOpConstructMat2x4:
1275 case glslang::EOpConstructMat3x2:
1276 case glslang::EOpConstructMat3x3:
1277 case glslang::EOpConstructMat3x4:
1278 case glslang::EOpConstructMat4x2:
1279 case glslang::EOpConstructMat4x3:
1280 case glslang::EOpConstructMat4x4:
1281 case glslang::EOpConstructDMat2x2:
1282 case glslang::EOpConstructDMat2x3:
1283 case glslang::EOpConstructDMat2x4:
1284 case glslang::EOpConstructDMat3x2:
1285 case glslang::EOpConstructDMat3x3:
1286 case glslang::EOpConstructDMat3x4:
1287 case glslang::EOpConstructDMat4x2:
1288 case glslang::EOpConstructDMat4x3:
1289 case glslang::EOpConstructDMat4x4:
1290 isMatrix = true;
1291 // fall through
1292 case glslang::EOpConstructFloat:
1293 case glslang::EOpConstructVec2:
1294 case glslang::EOpConstructVec3:
1295 case glslang::EOpConstructVec4:
1296 case glslang::EOpConstructDouble:
1297 case glslang::EOpConstructDVec2:
1298 case glslang::EOpConstructDVec3:
1299 case glslang::EOpConstructDVec4:
1300 case glslang::EOpConstructBool:
1301 case glslang::EOpConstructBVec2:
1302 case glslang::EOpConstructBVec3:
1303 case glslang::EOpConstructBVec4:
1304 case glslang::EOpConstructInt:
1305 case glslang::EOpConstructIVec2:
1306 case glslang::EOpConstructIVec3:
1307 case glslang::EOpConstructIVec4:
1308 case glslang::EOpConstructUint:
1309 case glslang::EOpConstructUVec2:
1310 case glslang::EOpConstructUVec3:
1311 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001312 case glslang::EOpConstructInt64:
1313 case glslang::EOpConstructI64Vec2:
1314 case glslang::EOpConstructI64Vec3:
1315 case glslang::EOpConstructI64Vec4:
1316 case glslang::EOpConstructUint64:
1317 case glslang::EOpConstructU64Vec2:
1318 case glslang::EOpConstructU64Vec3:
1319 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001320 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001321 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001322 {
1323 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001324 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001325 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1326 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001327 if (node->getOp() == glslang::EOpConstructTextureSampler)
1328 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1329 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001330 std::vector<spv::Id> constituents;
1331 for (int c = 0; c < (int)arguments.size(); ++c)
1332 constituents.push_back(arguments[c]);
1333 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001334 } else if (isMatrix)
1335 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1336 else
1337 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 builder.clearAccessChain();
1340 builder.setAccessChainRValue(constructed);
1341
1342 return false;
1343 }
1344
1345 // These six are component-wise compares with component-wise results.
1346 // Forward on to createBinaryOperation(), requesting a vector result.
1347 case glslang::EOpLessThan:
1348 case glslang::EOpGreaterThan:
1349 case glslang::EOpLessThanEqual:
1350 case glslang::EOpGreaterThanEqual:
1351 case glslang::EOpVectorEqual:
1352 case glslang::EOpVectorNotEqual:
1353 {
1354 // Map the operation to a binary
1355 binOp = node->getOp();
1356 reduceComparison = false;
1357 switch (node->getOp()) {
1358 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1359 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1360 default: binOp = node->getOp(); break;
1361 }
1362
1363 break;
1364 }
1365 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001366 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001367 binOp = glslang::EOpMul;
1368 break;
1369 case glslang::EOpOuterProduct:
1370 // two vectors multiplied to make a matrix
1371 binOp = glslang::EOpOuterProduct;
1372 break;
1373 case glslang::EOpDot:
1374 {
qining25262b32016-05-06 17:25:16 -04001375 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001376 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001377 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001378 binOp = glslang::EOpMul;
1379 break;
1380 }
1381 case glslang::EOpMod:
1382 // when an aggregate, this is the floating-point mod built-in function,
1383 // which can be emitted by the one in createBinaryOperation()
1384 binOp = glslang::EOpMod;
1385 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001386 case glslang::EOpEmitVertex:
1387 case glslang::EOpEndPrimitive:
1388 case glslang::EOpBarrier:
1389 case glslang::EOpMemoryBarrier:
1390 case glslang::EOpMemoryBarrierAtomicCounter:
1391 case glslang::EOpMemoryBarrierBuffer:
1392 case glslang::EOpMemoryBarrierImage:
1393 case glslang::EOpMemoryBarrierShared:
1394 case glslang::EOpGroupMemoryBarrier:
1395 noReturnValue = true;
1396 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1397 break;
1398
John Kessenich426394d2015-07-23 10:22:48 -06001399 case glslang::EOpAtomicAdd:
1400 case glslang::EOpAtomicMin:
1401 case glslang::EOpAtomicMax:
1402 case glslang::EOpAtomicAnd:
1403 case glslang::EOpAtomicOr:
1404 case glslang::EOpAtomicXor:
1405 case glslang::EOpAtomicExchange:
1406 case glslang::EOpAtomicCompSwap:
1407 atomic = true;
1408 break;
1409
John Kessenich140f3df2015-06-26 16:58:36 -06001410 default:
1411 break;
1412 }
1413
1414 //
1415 // See if it maps to a regular operation.
1416 //
John Kessenich140f3df2015-06-26 16:58:36 -06001417 if (binOp != glslang::EOpNull) {
1418 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1419 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1420 assert(left && right);
1421
1422 builder.clearAccessChain();
1423 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001424 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001425
1426 builder.clearAccessChain();
1427 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001428 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001429
qining25262b32016-05-06 17:25:16 -04001430 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1431 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001432 left->getType().getBasicType(), reduceComparison);
1433
1434 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001435 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 builder.clearAccessChain();
1437 builder.setAccessChainRValue(result);
1438
1439 return false;
1440 }
1441
John Kessenich426394d2015-07-23 10:22:48 -06001442 //
1443 // Create the list of operands.
1444 //
John Kessenich140f3df2015-06-26 16:58:36 -06001445 glslang::TIntermSequence& glslangOperands = node->getSequence();
1446 std::vector<spv::Id> operands;
1447 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1448 builder.clearAccessChain();
1449 glslangOperands[arg]->traverse(this);
1450
1451 // special case l-value operands; there are just a few
1452 bool lvalue = false;
1453 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001454 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001455 case glslang::EOpModf:
1456 if (arg == 1)
1457 lvalue = true;
1458 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001459 case glslang::EOpInterpolateAtSample:
1460 case glslang::EOpInterpolateAtOffset:
1461 if (arg == 0)
1462 lvalue = true;
1463 break;
Rex Xud4782c12015-09-06 16:30:11 +08001464 case glslang::EOpAtomicAdd:
1465 case glslang::EOpAtomicMin:
1466 case glslang::EOpAtomicMax:
1467 case glslang::EOpAtomicAnd:
1468 case glslang::EOpAtomicOr:
1469 case glslang::EOpAtomicXor:
1470 case glslang::EOpAtomicExchange:
1471 case glslang::EOpAtomicCompSwap:
1472 if (arg == 0)
1473 lvalue = true;
1474 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001475 case glslang::EOpAddCarry:
1476 case glslang::EOpSubBorrow:
1477 if (arg == 2)
1478 lvalue = true;
1479 break;
1480 case glslang::EOpUMulExtended:
1481 case glslang::EOpIMulExtended:
1482 if (arg >= 2)
1483 lvalue = true;
1484 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001485 default:
1486 break;
1487 }
1488 if (lvalue)
1489 operands.push_back(builder.accessChainGetLValue());
1490 else
John Kessenich32cfd492016-02-02 12:37:46 -07001491 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
John Kessenich426394d2015-07-23 10:22:48 -06001493
1494 if (atomic) {
1495 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001496 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001497 } else {
1498 // Pass through to generic operations.
1499 switch (glslangOperands.size()) {
1500 case 0:
1501 result = createNoArgOperation(node->getOp());
1502 break;
1503 case 1:
qining25262b32016-05-06 17:25:16 -04001504 result = createUnaryOperation(
1505 node->getOp(), precision,
1506 TranslateNoContractionDecoration(node->getType().getQualifier()),
1507 convertGlslangToSpvType(node->getType()), operands.front(),
1508 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001509 break;
1510 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001511 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001512 break;
1513 }
John Kessenich140f3df2015-06-26 16:58:36 -06001514 }
1515
1516 if (noReturnValue)
1517 return false;
1518
1519 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001520 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001521 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001522 } else {
1523 builder.clearAccessChain();
1524 builder.setAccessChainRValue(result);
1525 return false;
1526 }
1527}
1528
1529bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1530{
1531 // This path handles both if-then-else and ?:
1532 // The if-then-else has a node type of void, while
1533 // ?: has a non-void node type
1534 spv::Id result = 0;
1535 if (node->getBasicType() != glslang::EbtVoid) {
1536 // don't handle this as just on-the-fly temporaries, because there will be two names
1537 // and better to leave SSA to later passes
1538 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1539 }
1540
1541 // emit the condition before doing anything with selection
1542 node->getCondition()->traverse(this);
1543
1544 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001545 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001546
1547 if (node->getTrueBlock()) {
1548 // emit the "then" statement
1549 node->getTrueBlock()->traverse(this);
1550 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001551 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001552 }
1553
1554 if (node->getFalseBlock()) {
1555 ifBuilder.makeBeginElse();
1556 // emit the "else" statement
1557 node->getFalseBlock()->traverse(this);
1558 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001559 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001560 }
1561
1562 ifBuilder.makeEndIf();
1563
1564 if (result) {
1565 // GLSL only has r-values as the result of a :?, but
1566 // if we have an l-value, that can be more efficient if it will
1567 // become the base of a complex r-value expression, because the
1568 // next layer copies r-values into memory to use the access-chain mechanism
1569 builder.clearAccessChain();
1570 builder.setAccessChainLValue(result);
1571 }
1572
1573 return false;
1574}
1575
1576bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1577{
1578 // emit and get the condition before doing anything with switch
1579 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001580 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001581
1582 // browse the children to sort out code segments
1583 int defaultSegment = -1;
1584 std::vector<TIntermNode*> codeSegments;
1585 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1586 std::vector<int> caseValues;
1587 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1588 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1589 TIntermNode* child = *c;
1590 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001591 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001592 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001593 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001594 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1595 } else
1596 codeSegments.push_back(child);
1597 }
1598
qining25262b32016-05-06 17:25:16 -04001599 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001600 // statements between the last case and the end of the switch statement
1601 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1602 (int)codeSegments.size() == defaultSegment)
1603 codeSegments.push_back(nullptr);
1604
1605 // make the switch statement
1606 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001607 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001608
1609 // emit all the code in the segments
1610 breakForLoop.push(false);
1611 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1612 builder.nextSwitchSegment(segmentBlocks, s);
1613 if (codeSegments[s])
1614 codeSegments[s]->traverse(this);
1615 else
1616 builder.addSwitchBreak();
1617 }
1618 breakForLoop.pop();
1619
1620 builder.endSwitch(segmentBlocks);
1621
1622 return false;
1623}
1624
1625void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1626{
1627 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001628 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001629
1630 builder.clearAccessChain();
1631 builder.setAccessChainRValue(constant);
1632}
1633
1634bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1635{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001636 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001637 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001638 // Spec requires back edges to target header blocks, and every header block
1639 // must dominate its merge block. Make a header block first to ensure these
1640 // conditions are met. By definition, it will contain OpLoopMerge, followed
1641 // by a block-ending branch. But we don't want to put any other body/test
1642 // instructions in it, since the body/test may have arbitrary instructions,
1643 // including merges of its own.
1644 builder.setBuildPoint(&blocks.head);
1645 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001646 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001647 spv::Block& test = builder.makeNewBlock();
1648 builder.createBranch(&test);
1649
1650 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001651 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001652 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001653 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1655
1656 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001657 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001658 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001659 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001660 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001661 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001662
1663 builder.setBuildPoint(&blocks.continue_target);
1664 if (node->getTerminal())
1665 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001666 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001667 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001668 builder.createBranch(&blocks.body);
1669
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001670 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 builder.setBuildPoint(&blocks.body);
1672 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001673 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001674 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001675 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001676
1677 builder.setBuildPoint(&blocks.continue_target);
1678 if (node->getTerminal())
1679 node->getTerminal()->traverse(this);
1680 if (node->getTest()) {
1681 node->getTest()->traverse(this);
1682 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001683 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001684 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001685 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001686 // TODO: unless there was a break/return/discard instruction
1687 // somewhere in the body, this is an infinite loop, so we should
1688 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001689 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001690 }
John Kessenich140f3df2015-06-26 16:58:36 -06001691 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001692 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001693 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001694 return false;
1695}
1696
1697bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1698{
1699 if (node->getExpression())
1700 node->getExpression()->traverse(this);
1701
1702 switch (node->getFlowOp()) {
1703 case glslang::EOpKill:
1704 builder.makeDiscard();
1705 break;
1706 case glslang::EOpBreak:
1707 if (breakForLoop.top())
1708 builder.createLoopExit();
1709 else
1710 builder.addSwitchBreak();
1711 break;
1712 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001713 builder.createLoopContinue();
1714 break;
1715 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001716 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001717 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001718 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001719 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001720
1721 builder.clearAccessChain();
1722 break;
1723
1724 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001725 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001726 break;
1727 }
1728
1729 return false;
1730}
1731
1732spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1733{
qining25262b32016-05-06 17:25:16 -04001734 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001735 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001736 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001737 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001738 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 }
1740
1741 // Now, handle actual variables
1742 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1743 spv::Id spvType = convertGlslangToSpvType(node->getType());
1744
1745 const char* name = node->getName().c_str();
1746 if (glslang::IsAnonymous(name))
1747 name = "";
1748
1749 return builder.createVariable(storageClass, spvType, name);
1750}
1751
1752// Return type Id of the sampled type.
1753spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1754{
1755 switch (sampler.type) {
1756 case glslang::EbtFloat: return builder.makeFloatType(32);
1757 case glslang::EbtInt: return builder.makeIntType(32);
1758 case glslang::EbtUint: return builder.makeUintType(32);
1759 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001760 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001761 return builder.makeFloatType(32);
1762 }
1763}
1764
John Kessenich3ac051e2015-12-20 11:29:16 -07001765// Convert from a glslang type to an SPV type, by calling into a
1766// recursive version of this function. This establishes the inherited
1767// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001768spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1769{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001770 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001771}
1772
1773// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001774// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001775spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001776{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001777 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001778
1779 switch (type.getBasicType()) {
1780 case glslang::EbtVoid:
1781 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001782 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001783 break;
1784 case glslang::EbtFloat:
1785 spvType = builder.makeFloatType(32);
1786 break;
1787 case glslang::EbtDouble:
1788 spvType = builder.makeFloatType(64);
1789 break;
1790 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001791 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1792 // a 32-bit int where non-0 means true.
1793 if (explicitLayout != glslang::ElpNone)
1794 spvType = builder.makeUintType(32);
1795 else
1796 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001797 break;
1798 case glslang::EbtInt:
1799 spvType = builder.makeIntType(32);
1800 break;
1801 case glslang::EbtUint:
1802 spvType = builder.makeUintType(32);
1803 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001804 case glslang::EbtInt64:
1805 builder.addCapability(spv::CapabilityInt64);
1806 spvType = builder.makeIntType(64);
1807 break;
1808 case glslang::EbtUint64:
1809 builder.addCapability(spv::CapabilityInt64);
1810 spvType = builder.makeUintType(64);
1811 break;
John Kessenich426394d2015-07-23 10:22:48 -06001812 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001813 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 -06001814 spvType = builder.makeUintType(32);
1815 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001816 case glslang::EbtSampler:
1817 {
1818 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001819 if (sampler.sampler) {
1820 // pure sampler
1821 spvType = builder.makeSamplerType();
1822 } else {
1823 // an image is present, make its type
1824 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1825 sampler.image ? 2 : 1, TranslateImageFormat(type));
1826 if (sampler.combined) {
1827 // already has both image and sampler, make the combined type
1828 spvType = builder.makeSampledImageType(spvType);
1829 }
John Kessenich55e7d112015-11-15 21:33:39 -07001830 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001831 }
John Kessenich140f3df2015-06-26 16:58:36 -06001832 break;
1833 case glslang::EbtStruct:
1834 case glslang::EbtBlock:
1835 {
1836 // If we've seen this struct type, return it
1837 const glslang::TTypeList* glslangStruct = type.getStruct();
1838 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001839
1840 // Try to share structs for different layouts, but not yet for other
1841 // kinds of qualification (primarily not yet including interpolant qualification).
1842 if (! HasNonLayoutQualifiers(qualifier))
1843 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1844 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001845 break;
1846
1847 // else, we haven't seen it...
1848
1849 // Create a vector of struct types for SPIR-V to consume
1850 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1851 if (type.getBasicType() == glslang::EbtBlock)
1852 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001853 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001854 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1855 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1856 if (glslangType.hiddenMember()) {
1857 ++memberDelta;
1858 if (type.getBasicType() == glslang::EbtBlock)
1859 memberRemapper[glslangStruct][i] = -1;
1860 } else {
1861 if (type.getBasicType() == glslang::EbtBlock)
1862 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001863 // modify just this child's view of the qualifier
1864 glslang::TQualifier subQualifier = glslangType.getQualifier();
1865 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001866
1867 // manually inherit location; it's more complex
1868 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1869 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1870 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001871 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001872
1873 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001874 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
1876 }
1877
1878 // Make the SPIR-V type
1879 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001880 if (! HasNonLayoutQualifiers(qualifier))
1881 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001882
1883 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001884 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001885 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001886 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1887 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1888 int member = i;
1889 if (type.getBasicType() == glslang::EbtBlock)
1890 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001891
John Kesseniche0b6cad2015-12-24 10:30:13 -07001892 // modify just this child's view of the qualifier
1893 glslang::TQualifier subQualifier = glslangType.getQualifier();
1894 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001895
John Kessenich140f3df2015-06-26 16:58:36 -06001896 // using -1 above to indicate a hidden member
1897 if (member >= 0) {
1898 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001899 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001900 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001901 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001902 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001903 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
Rex Xubbceed72016-05-21 09:40:44 +08001904 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
scygan8add1512016-05-06 16:54:54 +02001905 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001906 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001907
Rex Xu1da878f2016-02-21 20:59:01 +08001908 if (qualifier.storage == glslang::EvqBuffer) {
1909 std::vector<spv::Decoration> memory;
1910 TranslateMemoryDecoration(subQualifier, memory);
1911 for (unsigned int i = 0; i < memory.size(); ++i)
1912 addMemberDecoration(spvType, member, memory[i]);
1913 }
1914
John Kessenich09677482016-02-19 12:21:50 -07001915 // compute location decoration; tricky based on whether inheritance is at play
1916 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1917 // probably move to the linker stage of the front end proper, and just have the
1918 // answer sitting already distributed throughout the individual member locations.
1919 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001920 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001921 // struct members should not have explicit locations
1922 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001923 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001924 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001925 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1926 // The members, and their nested types, must not themselves have Location decorations.
1927 }
John Kessenich09677482016-02-19 12:21:50 -07001928 else if (qualifier.hasLocation()) // inheritance
1929 location = qualifier.layoutLocation + locationOffset;
1930 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001931 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001932 if (location >= 0)
1933 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1934
1935 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001936 if (glslangType.getQualifier().hasComponent())
1937 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1938 if (glslangType.getQualifier().hasXfbOffset())
1939 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001940 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001941 // figure out what to do with offset, which is accumulating
1942 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001943 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001944 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001945 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001946 offset = nextOffset;
1947 }
John Kessenich140f3df2015-06-26 16:58:36 -06001948
John Kessenichf85e8062015-12-19 13:57:10 -07001949 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001950 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001951
John Kessenich140f3df2015-06-26 16:58:36 -06001952 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001953 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001954 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001955 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001956 }
1957 }
1958
1959 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001960 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001961 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001962 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001963 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001964 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001965 }
John Kessenich140f3df2015-06-26 16:58:36 -06001966 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001967 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001968 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001969 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 if (type.getQualifier().hasXfbBuffer())
1971 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1972 }
1973 }
1974 break;
1975 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001976 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001977 break;
1978 }
1979
1980 if (type.isMatrix())
1981 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1982 else {
1983 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1984 if (type.getVectorSize() > 1)
1985 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1986 }
1987
1988 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001989 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1990
John Kessenichc9a80832015-09-12 12:17:44 -06001991 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001992 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001993 // We need to decorate array strides for types needing explicit layout, except blocks.
1994 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001995 // Use a dummy glslang type for querying internal strides of
1996 // arrays of arrays, but using just a one-dimensional array.
1997 glslang::TType simpleArrayType(type, 0); // deference type of the array
1998 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1999 simpleArrayType.getArraySizes().dereference();
2000
2001 // Will compute the higher-order strides here, rather than making a whole
2002 // pile of types and doing repetitive recursion on their contents.
2003 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2004 }
John Kessenichf8842e52016-01-04 19:22:56 -07002005
2006 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002007 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002008 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002009 if (stride > 0)
2010 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002011 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002012 }
2013 } else {
2014 // single-dimensional array, and don't yet have stride
2015
John Kessenichf8842e52016-01-04 19:22:56 -07002016 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002017 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2018 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002019 }
John Kessenich31ed4832015-09-09 17:51:38 -06002020
John Kessenichc9a80832015-09-12 12:17:44 -06002021 // Do the outer dimension, which might not be known for a runtime-sized array
2022 if (type.isRuntimeSizedArray()) {
2023 spvType = builder.makeRuntimeArray(spvType);
2024 } else {
2025 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002026 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002027 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002028 if (stride > 0)
2029 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002030 }
2031
2032 return spvType;
2033}
2034
John Kessenich6c292d32016-02-15 20:58:50 -07002035// Turn the expression forming the array size into an id.
2036// This is not quite trivial, because of specialization constants.
2037// Sometimes, a raw constant is turned into an Id, and sometimes
2038// a specialization constant expression is.
2039spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2040{
2041 // First, see if this is sized with a node, meaning a specialization constant:
2042 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2043 if (specNode != nullptr) {
2044 builder.clearAccessChain();
2045 specNode->traverse(this);
2046 return accessChainLoad(specNode->getAsTyped()->getType());
2047 }
qining25262b32016-05-06 17:25:16 -04002048
John Kessenich6c292d32016-02-15 20:58:50 -07002049 // Otherwise, need a compile-time (front end) size, get it:
2050 int size = arraySizes.getDimSize(dim);
2051 assert(size > 0);
2052 return builder.makeUintConstant(size);
2053}
2054
John Kessenich103bef92016-02-08 21:38:15 -07002055// Wrap the builder's accessChainLoad to:
2056// - localize handling of RelaxedPrecision
2057// - use the SPIR-V inferred type instead of another conversion of the glslang type
2058// (avoids unnecessary work and possible type punning for structures)
2059// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002060spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2061{
John Kessenich103bef92016-02-08 21:38:15 -07002062 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2063 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2064
2065 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002066 if (type.getBasicType() == glslang::EbtBool) {
2067 if (builder.isScalarType(nominalTypeId)) {
2068 // Conversion for bool
2069 spv::Id boolType = builder.makeBoolType();
2070 if (nominalTypeId != boolType)
2071 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2072 } else if (builder.isVectorType(nominalTypeId)) {
2073 // Conversion for bvec
2074 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2075 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2076 if (nominalTypeId != bvecType)
2077 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2078 }
2079 }
John Kessenich103bef92016-02-08 21:38:15 -07002080
2081 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002082}
2083
Rex Xu27253232016-02-23 17:51:09 +08002084// Wrap the builder's accessChainStore to:
2085// - do conversion of concrete to abstract type
2086void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2087{
2088 // Need to convert to abstract types when necessary
2089 if (type.getBasicType() == glslang::EbtBool) {
2090 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2091
2092 if (builder.isScalarType(nominalTypeId)) {
2093 // Conversion for bool
2094 spv::Id boolType = builder.makeBoolType();
2095 if (nominalTypeId != boolType) {
2096 spv::Id zero = builder.makeUintConstant(0);
2097 spv::Id one = builder.makeUintConstant(1);
2098 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2099 }
2100 } else if (builder.isVectorType(nominalTypeId)) {
2101 // Conversion for bvec
2102 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2103 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2104 if (nominalTypeId != bvecType) {
2105 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2106 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2107 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2108 }
2109 }
2110 }
2111
2112 builder.accessChainStore(rvalue);
2113}
2114
John Kessenichf85e8062015-12-19 13:57:10 -07002115// Decide whether or not this type should be
2116// decorated with offsets and strides, and if so
2117// whether std140 or std430 rules should be applied.
2118glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002119{
John Kessenichf85e8062015-12-19 13:57:10 -07002120 // has to be a block
2121 if (type.getBasicType() != glslang::EbtBlock)
2122 return glslang::ElpNone;
2123
2124 // has to be a uniform or buffer block
2125 if (type.getQualifier().storage != glslang::EvqUniform &&
2126 type.getQualifier().storage != glslang::EvqBuffer)
2127 return glslang::ElpNone;
2128
2129 // return the layout to use
2130 switch (type.getQualifier().layoutPacking) {
2131 case glslang::ElpStd140:
2132 case glslang::ElpStd430:
2133 return type.getQualifier().layoutPacking;
2134 default:
2135 return glslang::ElpNone;
2136 }
John Kessenich31ed4832015-09-09 17:51:38 -06002137}
2138
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002139// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002140int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002141{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002142 int size;
John Kessenich49987892015-12-29 17:11:44 -07002143 int stride;
2144 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002145
2146 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002147}
2148
John Kessenich49987892015-12-29 17:11:44 -07002149// 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 -07002150// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002151int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002152{
John Kessenich49987892015-12-29 17:11:44 -07002153 glslang::TType elementType;
2154 elementType.shallowCopy(matrixType);
2155 elementType.clearArraySizes();
2156
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002157 int size;
John Kessenich49987892015-12-29 17:11:44 -07002158 int stride;
2159 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2160
2161 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002162}
2163
John Kessenich5e4b1242015-08-06 22:53:06 -06002164// Given a member type of a struct, realign the current offset for it, and compute
2165// the next (not yet aligned) offset for the next member, which will get aligned
2166// on the next call.
2167// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2168// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2169// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002170void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002171 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002172{
2173 // this will get a positive value when deemed necessary
2174 nextOffset = -1;
2175
John Kessenich5e4b1242015-08-06 22:53:06 -06002176 // override anything in currentOffset with user-set offset
2177 if (memberType.getQualifier().hasOffset())
2178 currentOffset = memberType.getQualifier().layoutOffset;
2179
2180 // It could be that current linker usage in glslang updated all the layoutOffset,
2181 // in which case the following code does not matter. But, that's not quite right
2182 // once cross-compilation unit GLSL validation is done, as the original user
2183 // settings are needed in layoutOffset, and then the following will come into play.
2184
John Kessenichf85e8062015-12-19 13:57:10 -07002185 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002186 if (! memberType.getQualifier().hasOffset())
2187 currentOffset = -1;
2188
2189 return;
2190 }
2191
John Kessenichf85e8062015-12-19 13:57:10 -07002192 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002193 if (currentOffset < 0)
2194 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002195
John Kessenich5e4b1242015-08-06 22:53:06 -06002196 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2197 // but possibly not yet correctly aligned.
2198
2199 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002200 int dummyStride;
2201 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002202 glslang::RoundToPow2(currentOffset, memberAlignment);
2203 nextOffset = currentOffset + memberSize;
2204}
2205
John Kessenichebb50532016-05-16 19:22:05 -06002206void TGlslangToSpvTraverser::declareClipCullCapability(const glslang::TTypeList& members, int member)
2207{
2208 if (members[member].type->getQualifier().builtIn == glslang::EbvClipDistance)
2209 builder.addCapability(spv::CapabilityClipDistance);
2210 if (members[member].type->getQualifier().builtIn == glslang::EbvCullDistance)
2211 builder.addCapability(spv::CapabilityCullDistance);
2212}
2213
John Kessenich140f3df2015-06-26 16:58:36 -06002214bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2215{
John Kessenich4d65ee32016-03-12 18:17:47 -07002216 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002217 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002218 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002219}
2220
2221// Make all the functions, skeletally, without actually visiting their bodies.
2222void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2223{
2224 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2225 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2226 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2227 continue;
2228
2229 // We're on a user function. Set up the basic interface for the function now,
2230 // so that it's available to call.
2231 // Translating the body will happen later.
2232 //
qining25262b32016-05-06 17:25:16 -04002233 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002234 // function. What it is an address of varies:
2235 //
2236 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2237 // so that write needs to be to a copy, hence the address of a copy works.
2238 //
2239 // - "const in" parameters can just be the r-value, as no writes need occur.
2240 //
2241 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2242 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2243
2244 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002245 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002246 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2247
2248 for (int p = 0; p < (int)parameters.size(); ++p) {
2249 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2250 spv::Id typeId = convertGlslangToSpvType(paramType);
2251 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2252 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2253 else
2254 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002255 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002256 paramTypes.push_back(typeId);
2257 }
2258
2259 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002260 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2261 convertGlslangToSpvType(glslFunction->getType()),
2262 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002263
2264 // Track function to emit/call later
2265 functionMap[glslFunction->getName().c_str()] = function;
2266
2267 // Set the parameter id's
2268 for (int p = 0; p < (int)parameters.size(); ++p) {
2269 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2270 // give a name too
2271 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2272 }
2273 }
2274}
2275
2276// Process all the initializers, while skipping the functions and link objects
2277void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2278{
2279 builder.setBuildPoint(shaderEntry->getLastBlock());
2280 for (int i = 0; i < (int)initializers.size(); ++i) {
2281 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2282 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2283
2284 // We're on a top-level node that's not a function. Treat as an initializer, whose
2285 // code goes into the beginning of main.
2286 initializer->traverse(this);
2287 }
2288 }
2289}
2290
2291// Process all the functions, while skipping initializers.
2292void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2293{
2294 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2295 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2296 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2297 node->traverse(this);
2298 }
2299}
2300
2301void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2302{
qining25262b32016-05-06 17:25:16 -04002303 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002304 // that called makeFunctions().
2305 spv::Function* function = functionMap[node->getName().c_str()];
2306 spv::Block* functionBlock = function->getEntryBlock();
2307 builder.setBuildPoint(functionBlock);
2308}
2309
Rex Xu04db3f52015-09-16 11:44:02 +08002310void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002311{
Rex Xufc618912015-09-09 16:42:49 +08002312 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002313
2314 glslang::TSampler sampler = {};
2315 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002316 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002317 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2318 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2319 }
2320
John Kessenich140f3df2015-06-26 16:58:36 -06002321 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2322 builder.clearAccessChain();
2323 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002324
2325 // Special case l-value operands
2326 bool lvalue = false;
2327 switch (node.getOp()) {
2328 case glslang::EOpImageAtomicAdd:
2329 case glslang::EOpImageAtomicMin:
2330 case glslang::EOpImageAtomicMax:
2331 case glslang::EOpImageAtomicAnd:
2332 case glslang::EOpImageAtomicOr:
2333 case glslang::EOpImageAtomicXor:
2334 case glslang::EOpImageAtomicExchange:
2335 case glslang::EOpImageAtomicCompSwap:
2336 if (i == 0)
2337 lvalue = true;
2338 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002339 case glslang::EOpSparseImageLoad:
2340 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2341 lvalue = true;
2342 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002343 case glslang::EOpSparseTexture:
2344 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2345 lvalue = true;
2346 break;
2347 case glslang::EOpSparseTextureClamp:
2348 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2349 lvalue = true;
2350 break;
2351 case glslang::EOpSparseTextureLod:
2352 case glslang::EOpSparseTextureOffset:
2353 if (i == 3)
2354 lvalue = true;
2355 break;
2356 case glslang::EOpSparseTextureFetch:
2357 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2358 lvalue = true;
2359 break;
2360 case glslang::EOpSparseTextureFetchOffset:
2361 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2362 lvalue = true;
2363 break;
2364 case glslang::EOpSparseTextureLodOffset:
2365 case glslang::EOpSparseTextureGrad:
2366 case glslang::EOpSparseTextureOffsetClamp:
2367 if (i == 4)
2368 lvalue = true;
2369 break;
2370 case glslang::EOpSparseTextureGradOffset:
2371 case glslang::EOpSparseTextureGradClamp:
2372 if (i == 5)
2373 lvalue = true;
2374 break;
2375 case glslang::EOpSparseTextureGradOffsetClamp:
2376 if (i == 6)
2377 lvalue = true;
2378 break;
2379 case glslang::EOpSparseTextureGather:
2380 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2381 lvalue = true;
2382 break;
2383 case glslang::EOpSparseTextureGatherOffset:
2384 case glslang::EOpSparseTextureGatherOffsets:
2385 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2386 lvalue = true;
2387 break;
Rex Xufc618912015-09-09 16:42:49 +08002388 default:
2389 break;
2390 }
2391
Rex Xu6b86d492015-09-16 17:48:22 +08002392 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002393 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002394 else
John Kessenich32cfd492016-02-02 12:37:46 -07002395 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002396 }
2397}
2398
John Kessenichfc51d282015-08-19 13:34:18 -06002399void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002400{
John Kessenichfc51d282015-08-19 13:34:18 -06002401 builder.clearAccessChain();
2402 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002403 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002404}
John Kessenich140f3df2015-06-26 16:58:36 -06002405
John Kessenichfc51d282015-08-19 13:34:18 -06002406spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2407{
Rex Xufc618912015-09-09 16:42:49 +08002408 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002409 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002410 }
2411
John Kessenichfc51d282015-08-19 13:34:18 -06002412 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002413 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2414 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2415 std::vector<spv::Id> arguments;
2416 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002417 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002418 else
2419 translateArguments(*node->getAsUnaryNode(), arguments);
2420 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2421
2422 spv::Builder::TextureParameters params = { };
2423 params.sampler = arguments[0];
2424
Rex Xu04db3f52015-09-16 11:44:02 +08002425 glslang::TCrackedTextureOp cracked;
2426 node->crackTexture(sampler, cracked);
2427
John Kessenichfc51d282015-08-19 13:34:18 -06002428 // Check for queries
2429 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002430 // a sampled image needs to have the image extracted first
2431 if (builder.isSampledImage(params.sampler))
2432 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002433 switch (node->getOp()) {
2434 case glslang::EOpImageQuerySize:
2435 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002436 if (arguments.size() > 1) {
2437 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002438 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002439 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002440 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002441 case glslang::EOpImageQuerySamples:
2442 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002443 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002444 case glslang::EOpTextureQueryLod:
2445 params.coords = arguments[1];
2446 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2447 case glslang::EOpTextureQueryLevels:
2448 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002449 case glslang::EOpSparseTexelsResident:
2450 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002451 default:
2452 assert(0);
2453 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 }
John Kessenich140f3df2015-06-26 16:58:36 -06002455 }
2456
Rex Xufc618912015-09-09 16:42:49 +08002457 // Check for image functions other than queries
2458 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002459 std::vector<spv::Id> operands;
2460 auto opIt = arguments.begin();
2461 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002462
2463 // Handle subpass operations
2464 // TODO: GLSL should change to have the "MS" only on the type rather than the
2465 // built-in function.
2466 if (cracked.subpass) {
2467 // add on the (0,0) coordinate
2468 spv::Id zero = builder.makeIntConstant(0);
2469 std::vector<spv::Id> comps;
2470 comps.push_back(zero);
2471 comps.push_back(zero);
2472 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2473 if (sampler.ms) {
2474 operands.push_back(spv::ImageOperandsSampleMask);
2475 operands.push_back(*(opIt++));
2476 }
2477 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2478 }
2479
John Kessenich56bab042015-09-16 10:54:31 -06002480 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002481 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002482 if (sampler.ms) {
2483 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002484 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002485 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002486 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2487 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002488 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002489 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002490 if (sampler.ms) {
2491 operands.push_back(*(opIt + 1));
2492 operands.push_back(spv::ImageOperandsSampleMask);
2493 operands.push_back(*opIt);
2494 } else
2495 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002496 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002497 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2498 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002499 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002500 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2501 builder.addCapability(spv::CapabilitySparseResidency);
2502 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2503 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2504
2505 if (sampler.ms) {
2506 operands.push_back(spv::ImageOperandsSampleMask);
2507 operands.push_back(*opIt++);
2508 }
2509
2510 // Create the return type that was a special structure
2511 spv::Id texelOut = *opIt;
2512 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2513 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2514 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2515
2516 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2517
2518 // Decode the return type
2519 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2520 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002521 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002522 // Process image atomic operations
2523
2524 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2525 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002526 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002527
Rex Xufc618912015-09-09 16:42:49 +08002528 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002529 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002530
2531 std::vector<spv::Id> operands;
2532 operands.push_back(pointer);
2533 for (; opIt != arguments.end(); ++opIt)
2534 operands.push_back(*opIt);
2535
Rex Xu04db3f52015-09-16 11:44:02 +08002536 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002537 }
2538 }
2539
2540 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002541 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002542 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2543
John Kessenichfc51d282015-08-19 13:34:18 -06002544 // check for bias argument
2545 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002546 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002547 int nonBiasArgCount = 2;
2548 if (cracked.offset)
2549 ++nonBiasArgCount;
2550 if (cracked.grad)
2551 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002552 if (cracked.lodClamp)
2553 ++nonBiasArgCount;
2554 if (sparse)
2555 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002556
2557 if ((int)arguments.size() > nonBiasArgCount)
2558 bias = true;
2559 }
2560
John Kessenichfc51d282015-08-19 13:34:18 -06002561 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002562
John Kessenichfc51d282015-08-19 13:34:18 -06002563 params.coords = arguments[1];
2564 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002565 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002566
2567 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002568 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002569 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002570 ++extraArgs;
2571 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002572 params.Dref = arguments[2];
2573 ++extraArgs;
2574 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002575 std::vector<spv::Id> indexes;
2576 int comp;
2577 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002578 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002579 else
2580 comp = builder.getNumComponents(params.coords) - 1;
2581 indexes.push_back(comp);
2582 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2583 }
2584 if (cracked.lod) {
2585 params.lod = arguments[2];
2586 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002587 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2588 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2589 noImplicitLod = true;
2590 }
2591 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002592 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002593 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002594 }
2595 if (cracked.grad) {
2596 params.gradX = arguments[2 + extraArgs];
2597 params.gradY = arguments[3 + extraArgs];
2598 extraArgs += 2;
2599 }
John Kessenich55e7d112015-11-15 21:33:39 -07002600 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002601 params.offset = arguments[2 + extraArgs];
2602 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002603 } else if (cracked.offsets) {
2604 params.offsets = arguments[2 + extraArgs];
2605 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002606 }
Rex Xu48edadf2015-12-31 16:11:41 +08002607 if (cracked.lodClamp) {
2608 params.lodClamp = arguments[2 + extraArgs];
2609 ++extraArgs;
2610 }
2611 if (sparse) {
2612 params.texelOut = arguments[2 + extraArgs];
2613 ++extraArgs;
2614 }
John Kessenichfc51d282015-08-19 13:34:18 -06002615 if (bias) {
2616 params.bias = arguments[2 + extraArgs];
2617 ++extraArgs;
2618 }
John Kessenich55e7d112015-11-15 21:33:39 -07002619 if (cracked.gather && ! sampler.shadow) {
2620 // default component is 0, if missing, otherwise an argument
2621 if (2 + extraArgs < (int)arguments.size()) {
2622 params.comp = arguments[2 + extraArgs];
2623 ++extraArgs;
2624 } else {
2625 params.comp = builder.makeIntConstant(0);
2626 }
2627 }
John Kessenichfc51d282015-08-19 13:34:18 -06002628
John Kessenich019f08f2016-02-15 15:40:42 -07002629 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002630}
2631
2632spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2633{
2634 // Grab the function's pointer from the previously created function
2635 spv::Function* function = functionMap[node->getName().c_str()];
2636 if (! function)
2637 return 0;
2638
2639 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2640 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2641
2642 // See comments in makeFunctions() for details about the semantics for parameter passing.
2643 //
2644 // These imply we need a four step process:
2645 // 1. Evaluate the arguments
2646 // 2. Allocate and make copies of in, out, and inout arguments
2647 // 3. Make the call
2648 // 4. Copy back the results
2649
2650 // 1. Evaluate the arguments
2651 std::vector<spv::Builder::AccessChain> lValues;
2652 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002653 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002654 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002655 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002656 // build l-value
2657 builder.clearAccessChain();
2658 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002659 argTypes.push_back(&paramType);
2660 // keep outputs as and samplers l-values, evaluate input-only as r-values
2661 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.getBasicType() == glslang::EbtSampler) {
John Kessenich140f3df2015-06-26 16:58:36 -06002662 // save l-value
2663 lValues.push_back(builder.getAccessChain());
2664 } else {
2665 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002666 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002667 }
2668 }
2669
2670 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2671 // copy the original into that space.
2672 //
2673 // Also, build up the list of actual arguments to pass in for the call
2674 int lValueCount = 0;
2675 int rValueCount = 0;
2676 std::vector<spv::Id> spvArgs;
2677 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002678 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002679 spv::Id arg;
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002680 if (paramType.getBasicType() == glslang::EbtSampler) {
2681 builder.setAccessChain(lValues[lValueCount]);
2682 arg = builder.accessChainGetLValue();
2683 ++lValueCount;
2684 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002685 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002686 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2687 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2688 // need to copy the input into output space
2689 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002690 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002691 builder.createStore(copy, arg);
2692 }
2693 ++lValueCount;
2694 } else {
2695 arg = rValues[rValueCount];
2696 ++rValueCount;
2697 }
2698 spvArgs.push_back(arg);
2699 }
2700
2701 // 3. Make the call.
2702 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002703 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002704
2705 // 4. Copy back out an "out" arguments.
2706 lValueCount = 0;
2707 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2708 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2709 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2710 spv::Id copy = builder.createLoad(spvArgs[a]);
2711 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002712 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002713 }
2714 ++lValueCount;
2715 }
2716 }
2717
2718 return result;
2719}
2720
2721// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002722spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2723 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002724 spv::Id typeId, spv::Id left, spv::Id right,
2725 glslang::TBasicType typeProxy, bool reduceComparison)
2726{
Rex Xu8ff43de2016-04-22 16:51:45 +08002727 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002728 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002729 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002730
2731 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002732 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002733 bool comparison = false;
2734
2735 switch (op) {
2736 case glslang::EOpAdd:
2737 case glslang::EOpAddAssign:
2738 if (isFloat)
2739 binOp = spv::OpFAdd;
2740 else
2741 binOp = spv::OpIAdd;
2742 break;
2743 case glslang::EOpSub:
2744 case glslang::EOpSubAssign:
2745 if (isFloat)
2746 binOp = spv::OpFSub;
2747 else
2748 binOp = spv::OpISub;
2749 break;
2750 case glslang::EOpMul:
2751 case glslang::EOpMulAssign:
2752 if (isFloat)
2753 binOp = spv::OpFMul;
2754 else
2755 binOp = spv::OpIMul;
2756 break;
2757 case glslang::EOpVectorTimesScalar:
2758 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002759 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002760 if (builder.isVector(right))
2761 std::swap(left, right);
2762 assert(builder.isScalar(right));
2763 needMatchingVectors = false;
2764 binOp = spv::OpVectorTimesScalar;
2765 } else
2766 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002767 break;
2768 case glslang::EOpVectorTimesMatrix:
2769 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002770 binOp = spv::OpVectorTimesMatrix;
2771 break;
2772 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002773 binOp = spv::OpMatrixTimesVector;
2774 break;
2775 case glslang::EOpMatrixTimesScalar:
2776 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002777 binOp = spv::OpMatrixTimesScalar;
2778 break;
2779 case glslang::EOpMatrixTimesMatrix:
2780 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002781 binOp = spv::OpMatrixTimesMatrix;
2782 break;
2783 case glslang::EOpOuterProduct:
2784 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002785 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002786 break;
2787
2788 case glslang::EOpDiv:
2789 case glslang::EOpDivAssign:
2790 if (isFloat)
2791 binOp = spv::OpFDiv;
2792 else if (isUnsigned)
2793 binOp = spv::OpUDiv;
2794 else
2795 binOp = spv::OpSDiv;
2796 break;
2797 case glslang::EOpMod:
2798 case glslang::EOpModAssign:
2799 if (isFloat)
2800 binOp = spv::OpFMod;
2801 else if (isUnsigned)
2802 binOp = spv::OpUMod;
2803 else
2804 binOp = spv::OpSMod;
2805 break;
2806 case glslang::EOpRightShift:
2807 case glslang::EOpRightShiftAssign:
2808 if (isUnsigned)
2809 binOp = spv::OpShiftRightLogical;
2810 else
2811 binOp = spv::OpShiftRightArithmetic;
2812 break;
2813 case glslang::EOpLeftShift:
2814 case glslang::EOpLeftShiftAssign:
2815 binOp = spv::OpShiftLeftLogical;
2816 break;
2817 case glslang::EOpAnd:
2818 case glslang::EOpAndAssign:
2819 binOp = spv::OpBitwiseAnd;
2820 break;
2821 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002822 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002823 binOp = spv::OpLogicalAnd;
2824 break;
2825 case glslang::EOpInclusiveOr:
2826 case glslang::EOpInclusiveOrAssign:
2827 binOp = spv::OpBitwiseOr;
2828 break;
2829 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002830 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002831 binOp = spv::OpLogicalOr;
2832 break;
2833 case glslang::EOpExclusiveOr:
2834 case glslang::EOpExclusiveOrAssign:
2835 binOp = spv::OpBitwiseXor;
2836 break;
2837 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002838 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002839 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002840 break;
2841
2842 case glslang::EOpLessThan:
2843 case glslang::EOpGreaterThan:
2844 case glslang::EOpLessThanEqual:
2845 case glslang::EOpGreaterThanEqual:
2846 case glslang::EOpEqual:
2847 case glslang::EOpNotEqual:
2848 case glslang::EOpVectorEqual:
2849 case glslang::EOpVectorNotEqual:
2850 comparison = true;
2851 break;
2852 default:
2853 break;
2854 }
2855
John Kessenich7c1aa102015-10-15 13:29:11 -06002856 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002857 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002858 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002859 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002860 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002861
2862 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002863 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002864 builder.promoteScalar(precision, left, right);
2865
qining25262b32016-05-06 17:25:16 -04002866 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2867 addDecoration(result, noContraction);
2868 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002869 }
2870
2871 if (! comparison)
2872 return 0;
2873
John Kessenich7c1aa102015-10-15 13:29:11 -06002874 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002875
2876 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2877 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2878
John Kessenich22118352015-12-21 20:54:09 -07002879 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002880 }
2881
2882 switch (op) {
2883 case glslang::EOpLessThan:
2884 if (isFloat)
2885 binOp = spv::OpFOrdLessThan;
2886 else if (isUnsigned)
2887 binOp = spv::OpULessThan;
2888 else
2889 binOp = spv::OpSLessThan;
2890 break;
2891 case glslang::EOpGreaterThan:
2892 if (isFloat)
2893 binOp = spv::OpFOrdGreaterThan;
2894 else if (isUnsigned)
2895 binOp = spv::OpUGreaterThan;
2896 else
2897 binOp = spv::OpSGreaterThan;
2898 break;
2899 case glslang::EOpLessThanEqual:
2900 if (isFloat)
2901 binOp = spv::OpFOrdLessThanEqual;
2902 else if (isUnsigned)
2903 binOp = spv::OpULessThanEqual;
2904 else
2905 binOp = spv::OpSLessThanEqual;
2906 break;
2907 case glslang::EOpGreaterThanEqual:
2908 if (isFloat)
2909 binOp = spv::OpFOrdGreaterThanEqual;
2910 else if (isUnsigned)
2911 binOp = spv::OpUGreaterThanEqual;
2912 else
2913 binOp = spv::OpSGreaterThanEqual;
2914 break;
2915 case glslang::EOpEqual:
2916 case glslang::EOpVectorEqual:
2917 if (isFloat)
2918 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002919 else if (isBool)
2920 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002921 else
2922 binOp = spv::OpIEqual;
2923 break;
2924 case glslang::EOpNotEqual:
2925 case glslang::EOpVectorNotEqual:
2926 if (isFloat)
2927 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002928 else if (isBool)
2929 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002930 else
2931 binOp = spv::OpINotEqual;
2932 break;
2933 default:
2934 break;
2935 }
2936
qining25262b32016-05-06 17:25:16 -04002937 if (binOp != spv::OpNop) {
2938 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2939 addDecoration(result, noContraction);
2940 return builder.setPrecision(result, precision);
2941 }
John Kessenich140f3df2015-06-26 16:58:36 -06002942
2943 return 0;
2944}
2945
John Kessenich04bb8a02015-12-12 12:28:14 -07002946//
2947// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2948// These can be any of:
2949//
2950// matrix * scalar
2951// scalar * matrix
2952// matrix * matrix linear algebraic
2953// matrix * vector
2954// vector * matrix
2955// matrix * matrix componentwise
2956// matrix op matrix op in {+, -, /}
2957// matrix op scalar op in {+, -, /}
2958// scalar op matrix op in {+, -, /}
2959//
qining25262b32016-05-06 17:25:16 -04002960spv::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 -07002961{
2962 bool firstClass = true;
2963
2964 // First, handle first-class matrix operations (* and matrix/scalar)
2965 switch (op) {
2966 case spv::OpFDiv:
2967 if (builder.isMatrix(left) && builder.isScalar(right)) {
2968 // turn matrix / scalar into a multiply...
2969 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2970 op = spv::OpMatrixTimesScalar;
2971 } else
2972 firstClass = false;
2973 break;
2974 case spv::OpMatrixTimesScalar:
2975 if (builder.isMatrix(right))
2976 std::swap(left, right);
2977 assert(builder.isScalar(right));
2978 break;
2979 case spv::OpVectorTimesMatrix:
2980 assert(builder.isVector(left));
2981 assert(builder.isMatrix(right));
2982 break;
2983 case spv::OpMatrixTimesVector:
2984 assert(builder.isMatrix(left));
2985 assert(builder.isVector(right));
2986 break;
2987 case spv::OpMatrixTimesMatrix:
2988 assert(builder.isMatrix(left));
2989 assert(builder.isMatrix(right));
2990 break;
2991 default:
2992 firstClass = false;
2993 break;
2994 }
2995
qining25262b32016-05-06 17:25:16 -04002996 if (firstClass) {
2997 spv::Id result = builder.createBinOp(op, typeId, left, right);
2998 addDecoration(result, noContraction);
2999 return builder.setPrecision(result, precision);
3000 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003001
3002 // Handle component-wise +, -, *, and / for all combinations of type.
3003 // The result type of all of them is the same type as the (a) matrix operand.
3004 // The algorithm is to:
3005 // - break the matrix(es) into vectors
3006 // - smear any scalar to a vector
3007 // - do vector operations
3008 // - make a matrix out the vector results
3009 switch (op) {
3010 case spv::OpFAdd:
3011 case spv::OpFSub:
3012 case spv::OpFDiv:
3013 case spv::OpFMul:
3014 {
3015 // one time set up...
3016 bool leftMat = builder.isMatrix(left);
3017 bool rightMat = builder.isMatrix(right);
3018 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3019 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3020 spv::Id scalarType = builder.getScalarTypeId(typeId);
3021 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3022 std::vector<spv::Id> results;
3023 spv::Id smearVec = spv::NoResult;
3024 if (builder.isScalar(left))
3025 smearVec = builder.smearScalar(precision, left, vecType);
3026 else if (builder.isScalar(right))
3027 smearVec = builder.smearScalar(precision, right, vecType);
3028
3029 // do each vector op
3030 for (unsigned int c = 0; c < numCols; ++c) {
3031 std::vector<unsigned int> indexes;
3032 indexes.push_back(c);
3033 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3034 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003035 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3036 addDecoration(result, noContraction);
3037 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003038 }
3039
3040 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003041 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003042 }
3043 default:
3044 assert(0);
3045 return spv::NoResult;
3046 }
3047}
3048
qining25262b32016-05-06 17:25:16 -04003049spv::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 -06003050{
3051 spv::Op unaryOp = spv::OpNop;
3052 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003053 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003054 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003055
3056 switch (op) {
3057 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003058 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003059 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003060 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003061 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003062 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003063 unaryOp = spv::OpSNegate;
3064 break;
3065
3066 case glslang::EOpLogicalNot:
3067 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003068 unaryOp = spv::OpLogicalNot;
3069 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003070 case glslang::EOpBitwiseNot:
3071 unaryOp = spv::OpNot;
3072 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003073
John Kessenich140f3df2015-06-26 16:58:36 -06003074 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003076 break;
3077 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003078 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003079 break;
3080 case glslang::EOpTranspose:
3081 unaryOp = spv::OpTranspose;
3082 break;
3083
3084 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003086 break;
3087 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003088 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003089 break;
3090 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003091 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003092 break;
3093 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003094 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003095 break;
3096 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003097 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003098 break;
3099 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003100 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003101 break;
3102 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003103 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003104 break;
3105 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003106 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003107 break;
3108
3109 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003110 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003111 break;
3112 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003114 break;
3115 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003116 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003117 break;
3118 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003119 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 break;
3124 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003125 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003126 break;
3127
3128 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134
3135 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003136 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003137 break;
3138 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003139 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003140 break;
3141 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003142 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003143 break;
3144 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003145 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003146 break;
3147 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003148 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003149 break;
3150 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003151 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003152 break;
3153
3154 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003155 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003161 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003162 break;
3163 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003164 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003165 break;
3166 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003167 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003168 break;
3169 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003170 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003171 break;
3172
3173 case glslang::EOpIsNan:
3174 unaryOp = spv::OpIsNan;
3175 break;
3176 case glslang::EOpIsInf:
3177 unaryOp = spv::OpIsInf;
3178 break;
3179
Rex Xucbc426e2015-12-15 16:03:10 +08003180 case glslang::EOpFloatBitsToInt:
3181 case glslang::EOpFloatBitsToUint:
3182 case glslang::EOpIntBitsToFloat:
3183 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003184 case glslang::EOpDoubleBitsToInt64:
3185 case glslang::EOpDoubleBitsToUint64:
3186 case glslang::EOpInt64BitsToDouble:
3187 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003188 unaryOp = spv::OpBitcast;
3189 break;
3190
John Kessenich140f3df2015-06-26 16:58:36 -06003191 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003193 break;
3194 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003195 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003196 break;
3197 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003198 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003202 break;
3203 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003204 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003205 break;
3206 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003208 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003209 case glslang::EOpPackSnorm4x8:
3210 libCall = spv::GLSLstd450PackSnorm4x8;
3211 break;
3212 case glslang::EOpUnpackSnorm4x8:
3213 libCall = spv::GLSLstd450UnpackSnorm4x8;
3214 break;
3215 case glslang::EOpPackUnorm4x8:
3216 libCall = spv::GLSLstd450PackUnorm4x8;
3217 break;
3218 case glslang::EOpUnpackUnorm4x8:
3219 libCall = spv::GLSLstd450UnpackUnorm4x8;
3220 break;
3221 case glslang::EOpPackDouble2x32:
3222 libCall = spv::GLSLstd450PackDouble2x32;
3223 break;
3224 case glslang::EOpUnpackDouble2x32:
3225 libCall = spv::GLSLstd450UnpackDouble2x32;
3226 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003227
Rex Xu8ff43de2016-04-22 16:51:45 +08003228 case glslang::EOpPackInt2x32:
3229 case glslang::EOpUnpackInt2x32:
3230 case glslang::EOpPackUint2x32:
3231 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003232 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003233 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3234 break;
3235
John Kessenich140f3df2015-06-26 16:58:36 -06003236 case glslang::EOpDPdx:
3237 unaryOp = spv::OpDPdx;
3238 break;
3239 case glslang::EOpDPdy:
3240 unaryOp = spv::OpDPdy;
3241 break;
3242 case glslang::EOpFwidth:
3243 unaryOp = spv::OpFwidth;
3244 break;
3245 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003246 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003247 unaryOp = spv::OpDPdxFine;
3248 break;
3249 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003250 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003251 unaryOp = spv::OpDPdyFine;
3252 break;
3253 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003254 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003255 unaryOp = spv::OpFwidthFine;
3256 break;
3257 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003258 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003259 unaryOp = spv::OpDPdxCoarse;
3260 break;
3261 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003262 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003263 unaryOp = spv::OpDPdyCoarse;
3264 break;
3265 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003266 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003267 unaryOp = spv::OpFwidthCoarse;
3268 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003269 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003270 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003271 libCall = spv::GLSLstd450InterpolateAtCentroid;
3272 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003273 case glslang::EOpAny:
3274 unaryOp = spv::OpAny;
3275 break;
3276 case glslang::EOpAll:
3277 unaryOp = spv::OpAll;
3278 break;
3279
3280 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003281 if (isFloat)
3282 libCall = spv::GLSLstd450FAbs;
3283 else
3284 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003285 break;
3286 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003287 if (isFloat)
3288 libCall = spv::GLSLstd450FSign;
3289 else
3290 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003291 break;
3292
John Kessenichfc51d282015-08-19 13:34:18 -06003293 case glslang::EOpAtomicCounterIncrement:
3294 case glslang::EOpAtomicCounterDecrement:
3295 case glslang::EOpAtomicCounter:
3296 {
3297 // Handle all of the atomics in one place, in createAtomicOperation()
3298 std::vector<spv::Id> operands;
3299 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003300 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003301 }
3302
John Kessenichfc51d282015-08-19 13:34:18 -06003303 case glslang::EOpBitFieldReverse:
3304 unaryOp = spv::OpBitReverse;
3305 break;
3306 case glslang::EOpBitCount:
3307 unaryOp = spv::OpBitCount;
3308 break;
3309 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003310 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003311 break;
3312 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003313 if (isUnsigned)
3314 libCall = spv::GLSLstd450FindUMsb;
3315 else
3316 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003317 break;
3318
Rex Xu574ab042016-04-14 16:53:07 +08003319 case glslang::EOpBallot:
3320 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003321 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003322 libCall = spv::GLSLstd450Bad;
3323 break;
3324
Rex Xu338b1852016-05-05 20:38:33 +08003325 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003326 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003327 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003328 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003329
John Kessenich140f3df2015-06-26 16:58:36 -06003330 default:
3331 return 0;
3332 }
3333
3334 spv::Id id;
3335 if (libCall >= 0) {
3336 std::vector<spv::Id> args;
3337 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003338 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003339 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003340 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003341 }
John Kessenich140f3df2015-06-26 16:58:36 -06003342
qining25262b32016-05-06 17:25:16 -04003343 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003344 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003345}
3346
John Kessenich7a53f762016-01-20 11:19:27 -07003347// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003348spv::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 -07003349{
3350 // Handle unary operations vector by vector.
3351 // The result type is the same type as the original type.
3352 // The algorithm is to:
3353 // - break the matrix into vectors
3354 // - apply the operation to each vector
3355 // - make a matrix out the vector results
3356
3357 // get the types sorted out
3358 int numCols = builder.getNumColumns(operand);
3359 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003360 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3361 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003362 std::vector<spv::Id> results;
3363
3364 // do each vector op
3365 for (int c = 0; c < numCols; ++c) {
3366 std::vector<unsigned int> indexes;
3367 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003368 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3369 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3370 addDecoration(destVec, noContraction);
3371 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003372 }
3373
3374 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003375 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003376}
3377
Rex Xu73e3ce72016-04-27 18:48:17 +08003378spv::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 -06003379{
3380 spv::Op convOp = spv::OpNop;
3381 spv::Id zero = 0;
3382 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003383 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003384
3385 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3386
3387 switch (op) {
3388 case glslang::EOpConvIntToBool:
3389 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003390 case glslang::EOpConvInt64ToBool:
3391 case glslang::EOpConvUint64ToBool:
3392 zero = (op == glslang::EOpConvInt64ToBool ||
3393 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003394 zero = makeSmearedConstant(zero, vectorSize);
3395 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3396
3397 case glslang::EOpConvFloatToBool:
3398 zero = builder.makeFloatConstant(0.0F);
3399 zero = makeSmearedConstant(zero, vectorSize);
3400 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3401
3402 case glslang::EOpConvDoubleToBool:
3403 zero = builder.makeDoubleConstant(0.0);
3404 zero = makeSmearedConstant(zero, vectorSize);
3405 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3406
3407 case glslang::EOpConvBoolToFloat:
3408 convOp = spv::OpSelect;
3409 zero = builder.makeFloatConstant(0.0);
3410 one = builder.makeFloatConstant(1.0);
3411 break;
3412 case glslang::EOpConvBoolToDouble:
3413 convOp = spv::OpSelect;
3414 zero = builder.makeDoubleConstant(0.0);
3415 one = builder.makeDoubleConstant(1.0);
3416 break;
3417 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003418 case glslang::EOpConvBoolToInt64:
3419 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3420 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003421 convOp = spv::OpSelect;
3422 break;
3423 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003424 case glslang::EOpConvBoolToUint64:
3425 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3426 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003427 convOp = spv::OpSelect;
3428 break;
3429
3430 case glslang::EOpConvIntToFloat:
3431 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003432 case glslang::EOpConvInt64ToFloat:
3433 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003434 convOp = spv::OpConvertSToF;
3435 break;
3436
3437 case glslang::EOpConvUintToFloat:
3438 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003439 case glslang::EOpConvUint64ToFloat:
3440 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003441 convOp = spv::OpConvertUToF;
3442 break;
3443
3444 case glslang::EOpConvDoubleToFloat:
3445 case glslang::EOpConvFloatToDouble:
3446 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003447 if (builder.isMatrixType(destType))
3448 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003449 break;
3450
3451 case glslang::EOpConvFloatToInt:
3452 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003453 case glslang::EOpConvFloatToInt64:
3454 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003455 convOp = spv::OpConvertFToS;
3456 break;
3457
3458 case glslang::EOpConvUintToInt:
3459 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003460 case glslang::EOpConvUint64ToInt64:
3461 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003462 if (builder.isInSpecConstCodeGenMode()) {
3463 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003464 zero = (op == glslang::EOpConvUintToInt64 ||
3465 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003466 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003467 // Use OpIAdd, instead of OpBitcast to do the conversion when
3468 // generating for OpSpecConstantOp instruction.
3469 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3470 }
3471 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003472 convOp = spv::OpBitcast;
3473 break;
3474
3475 case glslang::EOpConvFloatToUint:
3476 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003477 case glslang::EOpConvFloatToUint64:
3478 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003479 convOp = spv::OpConvertFToU;
3480 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003481
3482 case glslang::EOpConvIntToInt64:
3483 case glslang::EOpConvInt64ToInt:
3484 convOp = spv::OpSConvert;
3485 break;
3486
3487 case glslang::EOpConvUintToUint64:
3488 case glslang::EOpConvUint64ToUint:
3489 convOp = spv::OpUConvert;
3490 break;
3491
3492 case glslang::EOpConvIntToUint64:
3493 case glslang::EOpConvInt64ToUint:
3494 case glslang::EOpConvUint64ToInt:
3495 case glslang::EOpConvUintToInt64:
3496 // OpSConvert/OpUConvert + OpBitCast
3497 switch (op) {
3498 case glslang::EOpConvIntToUint64:
3499 convOp = spv::OpSConvert;
3500 type = builder.makeIntType(64);
3501 break;
3502 case glslang::EOpConvInt64ToUint:
3503 convOp = spv::OpSConvert;
3504 type = builder.makeIntType(32);
3505 break;
3506 case glslang::EOpConvUint64ToInt:
3507 convOp = spv::OpUConvert;
3508 type = builder.makeUintType(32);
3509 break;
3510 case glslang::EOpConvUintToInt64:
3511 convOp = spv::OpUConvert;
3512 type = builder.makeUintType(64);
3513 break;
3514 default:
3515 assert(0);
3516 break;
3517 }
3518
3519 if (vectorSize > 0)
3520 type = builder.makeVectorType(type, vectorSize);
3521
3522 operand = builder.createUnaryOp(convOp, type, operand);
3523
3524 if (builder.isInSpecConstCodeGenMode()) {
3525 // Build zero scalar or vector for OpIAdd.
3526 zero = (op == glslang::EOpConvIntToUint64 ||
3527 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3528 zero = makeSmearedConstant(zero, vectorSize);
3529 // Use OpIAdd, instead of OpBitcast to do the conversion when
3530 // generating for OpSpecConstantOp instruction.
3531 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3532 }
3533 // For normal run-time conversion instruction, use OpBitcast.
3534 convOp = spv::OpBitcast;
3535 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003536 default:
3537 break;
3538 }
3539
3540 spv::Id result = 0;
3541 if (convOp == spv::OpNop)
3542 return result;
3543
3544 if (convOp == spv::OpSelect) {
3545 zero = makeSmearedConstant(zero, vectorSize);
3546 one = makeSmearedConstant(one, vectorSize);
3547 result = builder.createTriOp(convOp, destType, operand, one, zero);
3548 } else
3549 result = builder.createUnaryOp(convOp, destType, operand);
3550
John Kessenich32cfd492016-02-02 12:37:46 -07003551 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003552}
3553
3554spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3555{
3556 if (vectorSize == 0)
3557 return constant;
3558
3559 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3560 std::vector<spv::Id> components;
3561 for (int c = 0; c < vectorSize; ++c)
3562 components.push_back(constant);
3563 return builder.makeCompositeConstant(vectorTypeId, components);
3564}
3565
John Kessenich426394d2015-07-23 10:22:48 -06003566// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003567spv::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 -06003568{
3569 spv::Op opCode = spv::OpNop;
3570
3571 switch (op) {
3572 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003573 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003574 opCode = spv::OpAtomicIAdd;
3575 break;
3576 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003577 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003578 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003579 break;
3580 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003581 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003582 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003583 break;
3584 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003585 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003586 opCode = spv::OpAtomicAnd;
3587 break;
3588 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003589 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003590 opCode = spv::OpAtomicOr;
3591 break;
3592 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003593 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003594 opCode = spv::OpAtomicXor;
3595 break;
3596 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003597 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003598 opCode = spv::OpAtomicExchange;
3599 break;
3600 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003601 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003602 opCode = spv::OpAtomicCompareExchange;
3603 break;
3604 case glslang::EOpAtomicCounterIncrement:
3605 opCode = spv::OpAtomicIIncrement;
3606 break;
3607 case glslang::EOpAtomicCounterDecrement:
3608 opCode = spv::OpAtomicIDecrement;
3609 break;
3610 case glslang::EOpAtomicCounter:
3611 opCode = spv::OpAtomicLoad;
3612 break;
3613 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003614 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003615 break;
3616 }
3617
3618 // Sort out the operands
3619 // - mapping from glslang -> SPV
3620 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003621 // - compare-exchange swaps the value and comparator
3622 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003623 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3624 auto opIt = operands.begin(); // walk the glslang operands
3625 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003626 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3627 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3628 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003629 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3630 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003631 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003632 spvAtomicOperands.push_back(*(opIt + 1));
3633 spvAtomicOperands.push_back(*opIt);
3634 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003635 }
John Kessenich426394d2015-07-23 10:22:48 -06003636
John Kessenich3e60a6f2015-09-14 22:45:16 -06003637 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003638 for (; opIt != operands.end(); ++opIt)
3639 spvAtomicOperands.push_back(*opIt);
3640
3641 return builder.createOp(opCode, typeId, spvAtomicOperands);
3642}
3643
John Kessenich91cef522016-05-05 16:45:40 -06003644// Create group invocation operations.
3645spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3646{
3647 builder.addCapability(spv::CapabilityGroups);
3648
3649 std::vector<spv::Id> operands;
3650 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3651 operands.push_back(operand);
3652
3653 switch (op) {
3654 case glslang::EOpAnyInvocation:
3655 case glslang::EOpAllInvocations:
3656 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3657
3658 case glslang::EOpAllInvocationsEqual:
3659 {
3660 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3661 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3662
3663 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3664 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3665 }
3666 default:
3667 logger->missingFunctionality("invocation operation");
3668 return spv::NoResult;
3669 }
3670}
3671
John Kessenich5e4b1242015-08-06 22:53:06 -06003672spv::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 -06003673{
Rex Xu8ff43de2016-04-22 16:51:45 +08003674 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003675 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3676
John Kessenich140f3df2015-06-26 16:58:36 -06003677 spv::Op opCode = spv::OpNop;
3678 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003679 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003680 spv::Id typeId0 = 0;
3681 if (consumedOperands > 0)
3682 typeId0 = builder.getTypeId(operands[0]);
3683 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003684
3685 switch (op) {
3686 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003687 if (isFloat)
3688 libCall = spv::GLSLstd450FMin;
3689 else if (isUnsigned)
3690 libCall = spv::GLSLstd450UMin;
3691 else
3692 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003693 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 if (isFloat)
3700 libCall = spv::GLSLstd450FMax;
3701 else if (isUnsigned)
3702 libCall = spv::GLSLstd450UMax;
3703 else
3704 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003705 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EOpDot:
3711 opCode = spv::OpDot;
3712 break;
3713 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003714 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
3716
3717 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 if (isFloat)
3719 libCall = spv::GLSLstd450FClamp;
3720 else if (isUnsigned)
3721 libCall = spv::GLSLstd450UClamp;
3722 else
3723 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003724 builder.promoteScalar(precision, operands.front(), operands[1]);
3725 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003728 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3729 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003730 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003731 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003732 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003733 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003734 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003735 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003736 break;
3737 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003738 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003739 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003740 break;
3741 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003742 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003743 builder.promoteScalar(precision, operands[0], operands[2]);
3744 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003745 break;
3746
3747 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003757 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003758 break;
3759 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003760 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003761 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003762 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003763 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003764 libCall = spv::GLSLstd450InterpolateAtSample;
3765 break;
3766 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003767 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003768 libCall = spv::GLSLstd450InterpolateAtOffset;
3769 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003770 case glslang::EOpAddCarry:
3771 opCode = spv::OpIAddCarry;
3772 typeId = builder.makeStructResultType(typeId0, typeId0);
3773 consumedOperands = 2;
3774 break;
3775 case glslang::EOpSubBorrow:
3776 opCode = spv::OpISubBorrow;
3777 typeId = builder.makeStructResultType(typeId0, typeId0);
3778 consumedOperands = 2;
3779 break;
3780 case glslang::EOpUMulExtended:
3781 opCode = spv::OpUMulExtended;
3782 typeId = builder.makeStructResultType(typeId0, typeId0);
3783 consumedOperands = 2;
3784 break;
3785 case glslang::EOpIMulExtended:
3786 opCode = spv::OpSMulExtended;
3787 typeId = builder.makeStructResultType(typeId0, typeId0);
3788 consumedOperands = 2;
3789 break;
3790 case glslang::EOpBitfieldExtract:
3791 if (isUnsigned)
3792 opCode = spv::OpBitFieldUExtract;
3793 else
3794 opCode = spv::OpBitFieldSExtract;
3795 break;
3796 case glslang::EOpBitfieldInsert:
3797 opCode = spv::OpBitFieldInsert;
3798 break;
3799
3800 case glslang::EOpFma:
3801 libCall = spv::GLSLstd450Fma;
3802 break;
3803 case glslang::EOpFrexp:
3804 libCall = spv::GLSLstd450FrexpStruct;
3805 if (builder.getNumComponents(operands[0]) == 1)
3806 frexpIntType = builder.makeIntegerType(32, true);
3807 else
3808 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3809 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3810 consumedOperands = 1;
3811 break;
3812 case glslang::EOpLdexp:
3813 libCall = spv::GLSLstd450Ldexp;
3814 break;
3815
Rex Xu574ab042016-04-14 16:53:07 +08003816 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003817 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003818 libCall = spv::GLSLstd450Bad;
3819 break;
3820
John Kessenich140f3df2015-06-26 16:58:36 -06003821 default:
3822 return 0;
3823 }
3824
3825 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003826 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003827 // Use an extended instruction from the standard library.
3828 // Construct the call arguments, without modifying the original operands vector.
3829 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3830 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003831 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003832 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003833 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003834 case 0:
3835 // should all be handled by visitAggregate and createNoArgOperation
3836 assert(0);
3837 return 0;
3838 case 1:
3839 // should all be handled by createUnaryOperation
3840 assert(0);
3841 return 0;
3842 case 2:
3843 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3844 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003845 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003846 // anything 3 or over doesn't have l-value operands, so all should be consumed
3847 assert(consumedOperands == operands.size());
3848 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003849 break;
3850 }
3851 }
3852
John Kessenich55e7d112015-11-15 21:33:39 -07003853 // Decode the return types that were structures
3854 switch (op) {
3855 case glslang::EOpAddCarry:
3856 case glslang::EOpSubBorrow:
3857 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3858 id = builder.createCompositeExtract(id, typeId0, 0);
3859 break;
3860 case glslang::EOpUMulExtended:
3861 case glslang::EOpIMulExtended:
3862 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3863 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3864 break;
3865 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003866 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003867 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3868 id = builder.createCompositeExtract(id, typeId0, 0);
3869 break;
3870 default:
3871 break;
3872 }
3873
John Kessenich32cfd492016-02-02 12:37:46 -07003874 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003875}
3876
3877// Intrinsics with no arguments, no return value, and no precision.
3878spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3879{
3880 // TODO: get the barrier operands correct
3881
3882 switch (op) {
3883 case glslang::EOpEmitVertex:
3884 builder.createNoResultOp(spv::OpEmitVertex);
3885 return 0;
3886 case glslang::EOpEndPrimitive:
3887 builder.createNoResultOp(spv::OpEndPrimitive);
3888 return 0;
3889 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003890 if (glslangIntermediate->getProfile() != EEsProfile)
3891 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003892 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003893 return 0;
3894 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003895 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 return 0;
3897 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003898 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003899 return 0;
3900 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003901 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003902 return 0;
3903 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003904 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003905 return 0;
3906 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003907 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003908 return 0;
3909 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003910 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003911 return 0;
3912 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003913 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003914 return 0;
3915 }
3916}
3917
3918spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3919{
John Kessenich2f273362015-07-18 22:34:27 -06003920 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003921 spv::Id id;
3922 if (symbolValues.end() != iter) {
3923 id = iter->second;
3924 return id;
3925 }
3926
3927 // it was not found, create it
3928 id = createSpvVariable(symbol);
3929 symbolValues[symbol->getId()] = id;
3930
3931 if (! symbol->getType().isStruct()) {
3932 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003933 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003934 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003935 if (symbol->getType().getQualifier().hasSpecConstantId())
3936 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003937 if (symbol->getQualifier().hasIndex())
3938 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3939 if (symbol->getQualifier().hasComponent())
3940 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3941 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003942 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003943 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003944 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003945 if (symbol->getQualifier().hasXfbBuffer())
3946 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3947 if (symbol->getQualifier().hasXfbOffset())
3948 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3949 }
3950 }
3951
scygan2c864272016-05-18 18:09:17 +02003952 if (symbol->getQualifier().hasLocation())
3953 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003954 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003955 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003956 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003957 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003958 }
John Kessenich140f3df2015-06-26 16:58:36 -06003959 if (symbol->getQualifier().hasSet())
3960 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003961 else if (IsDescriptorResource(symbol->getType())) {
3962 // default to 0
3963 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3964 }
John Kessenich140f3df2015-06-26 16:58:36 -06003965 if (symbol->getQualifier().hasBinding())
3966 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003967 if (symbol->getQualifier().hasAttachment())
3968 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003969 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003970 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003971 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003972 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003973 if (symbol->getQualifier().hasXfbBuffer())
3974 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3975 }
3976
Rex Xu1da878f2016-02-21 20:59:01 +08003977 if (symbol->getType().isImage()) {
3978 std::vector<spv::Decoration> memory;
3979 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3980 for (unsigned int i = 0; i < memory.size(); ++i)
3981 addDecoration(id, memory[i]);
3982 }
3983
John Kessenich140f3df2015-06-26 16:58:36 -06003984 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003985 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003986 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003987 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003988
John Kessenich140f3df2015-06-26 16:58:36 -06003989 return id;
3990}
3991
John Kessenich55e7d112015-11-15 21:33:39 -07003992// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003993void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3994{
3995 if (dec != spv::BadValue)
3996 builder.addDecoration(id, dec);
3997}
3998
John Kessenich55e7d112015-11-15 21:33:39 -07003999// If 'dec' is valid, add a one-operand decoration to an object
4000void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4001{
4002 if (dec != spv::BadValue)
4003 builder.addDecoration(id, dec, value);
4004}
4005
4006// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004007void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4008{
4009 if (dec != spv::BadValue)
4010 builder.addMemberDecoration(id, (unsigned)member, dec);
4011}
4012
John Kessenich92187592016-02-01 13:45:25 -07004013// If 'dec' is valid, add a one-operand decoration to a struct member
4014void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4015{
4016 if (dec != spv::BadValue)
4017 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4018}
4019
John Kessenich55e7d112015-11-15 21:33:39 -07004020// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004021// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004022//
4023// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4024//
4025// Recursively walk the nodes. The nodes form a tree whose leaves are
4026// regular constants, which themselves are trees that createSpvConstant()
4027// recursively walks. So, this function walks the "top" of the tree:
4028// - emit specialization constant-building instructions for specConstant
4029// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004030spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004031{
John Kessenich7cc0e282016-03-20 00:46:02 -06004032 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004033
qining4f4bb812016-04-03 23:55:17 -04004034 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004035 if (! node.getQualifier().specConstant) {
4036 // hand off to the non-spec-constant path
4037 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4038 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004039 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004040 nextConst, false);
4041 }
4042
4043 // We now know we have a specialization constant to build
4044
qining4f4bb812016-04-03 23:55:17 -04004045 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
4046 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4047 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4048 std::vector<spv::Id> dimConstId;
4049 for (int dim = 0; dim < 3; ++dim) {
4050 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4051 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4052 if (specConst)
4053 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4054 }
4055 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4056 }
4057
4058 // An AST node labelled as specialization constant should be a symbol node.
4059 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4060 if (auto* sn = node.getAsSymbolNode()) {
4061 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004062 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4063 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4064 // will set the builder into spec constant op instruction generating mode.
4065 sub_tree->traverse(this);
4066 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004067 } else if (auto* const_union_array = &sn->getConstArray()){
4068 int nextConst = 0;
4069 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004070 }
4071 }
qining4f4bb812016-04-03 23:55:17 -04004072
4073 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4074 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004075 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004076 exit(1);
4077 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004078}
4079
John Kessenich140f3df2015-06-26 16:58:36 -06004080// Use 'consts' as the flattened glslang source of scalar constants to recursively
4081// build the aggregate SPIR-V constant.
4082//
4083// If there are not enough elements present in 'consts', 0 will be substituted;
4084// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4085//
qining08408382016-03-21 09:51:37 -04004086spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004087{
4088 // vector of constants for SPIR-V
4089 std::vector<spv::Id> spvConsts;
4090
4091 // Type is used for struct and array constants
4092 spv::Id typeId = convertGlslangToSpvType(glslangType);
4093
4094 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004095 glslang::TType elementType(glslangType, 0);
4096 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004097 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004098 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004099 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004100 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004101 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004102 } else if (glslangType.getStruct()) {
4103 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4104 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004105 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004106 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004107 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4108 bool zero = nextConst >= consts.size();
4109 switch (glslangType.getBasicType()) {
4110 case glslang::EbtInt:
4111 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4112 break;
4113 case glslang::EbtUint:
4114 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4115 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004116 case glslang::EbtInt64:
4117 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4118 break;
4119 case glslang::EbtUint64:
4120 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4121 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004122 case glslang::EbtFloat:
4123 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4124 break;
4125 case glslang::EbtDouble:
4126 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4127 break;
4128 case glslang::EbtBool:
4129 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4130 break;
4131 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004132 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 }
4135 ++nextConst;
4136 }
4137 } else {
4138 // we have a non-aggregate (scalar) constant
4139 bool zero = nextConst >= consts.size();
4140 spv::Id scalar = 0;
4141 switch (glslangType.getBasicType()) {
4142 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004143 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004144 break;
4145 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004146 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004147 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004148 case glslang::EbtInt64:
4149 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4150 break;
4151 case glslang::EbtUint64:
4152 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4153 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004154 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004155 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004156 break;
4157 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004158 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004159 break;
4160 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004161 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004162 break;
4163 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004164 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004165 break;
4166 }
4167 ++nextConst;
4168 return scalar;
4169 }
4170
4171 return builder.makeCompositeConstant(typeId, spvConsts);
4172}
4173
John Kessenich7c1aa102015-10-15 13:29:11 -06004174// Return true if the node is a constant or symbol whose reading has no
4175// non-trivial observable cost or effect.
4176bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4177{
4178 // don't know what this is
4179 if (node == nullptr)
4180 return false;
4181
4182 // a constant is safe
4183 if (node->getAsConstantUnion() != nullptr)
4184 return true;
4185
4186 // not a symbol means non-trivial
4187 if (node->getAsSymbolNode() == nullptr)
4188 return false;
4189
4190 // a symbol, depends on what's being read
4191 switch (node->getType().getQualifier().storage) {
4192 case glslang::EvqTemporary:
4193 case glslang::EvqGlobal:
4194 case glslang::EvqIn:
4195 case glslang::EvqInOut:
4196 case glslang::EvqConst:
4197 case glslang::EvqConstReadOnly:
4198 case glslang::EvqUniform:
4199 return true;
4200 default:
4201 return false;
4202 }
qining25262b32016-05-06 17:25:16 -04004203}
John Kessenich7c1aa102015-10-15 13:29:11 -06004204
4205// A node is trivial if it is a single operation with no side effects.
4206// Error on the side of saying non-trivial.
4207// Return true if trivial.
4208bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4209{
4210 if (node == nullptr)
4211 return false;
4212
4213 // symbols and constants are trivial
4214 if (isTrivialLeaf(node))
4215 return true;
4216
4217 // otherwise, it needs to be a simple operation or one or two leaf nodes
4218
4219 // not a simple operation
4220 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4221 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4222 if (binaryNode == nullptr && unaryNode == nullptr)
4223 return false;
4224
4225 // not on leaf nodes
4226 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4227 return false;
4228
4229 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4230 return false;
4231 }
4232
4233 switch (node->getAsOperator()->getOp()) {
4234 case glslang::EOpLogicalNot:
4235 case glslang::EOpConvIntToBool:
4236 case glslang::EOpConvUintToBool:
4237 case glslang::EOpConvFloatToBool:
4238 case glslang::EOpConvDoubleToBool:
4239 case glslang::EOpEqual:
4240 case glslang::EOpNotEqual:
4241 case glslang::EOpLessThan:
4242 case glslang::EOpGreaterThan:
4243 case glslang::EOpLessThanEqual:
4244 case glslang::EOpGreaterThanEqual:
4245 case glslang::EOpIndexDirect:
4246 case glslang::EOpIndexDirectStruct:
4247 case glslang::EOpLogicalXor:
4248 case glslang::EOpAny:
4249 case glslang::EOpAll:
4250 return true;
4251 default:
4252 return false;
4253 }
4254}
4255
4256// Emit short-circuiting code, where 'right' is never evaluated unless
4257// the left side is true (for &&) or false (for ||).
4258spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4259{
4260 spv::Id boolTypeId = builder.makeBoolType();
4261
4262 // emit left operand
4263 builder.clearAccessChain();
4264 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004265 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004266
4267 // Operands to accumulate OpPhi operands
4268 std::vector<spv::Id> phiOperands;
4269 // accumulate left operand's phi information
4270 phiOperands.push_back(leftId);
4271 phiOperands.push_back(builder.getBuildPoint()->getId());
4272
4273 // Make the two kinds of operation symmetric with a "!"
4274 // || => emit "if (! left) result = right"
4275 // && => emit "if ( left) result = right"
4276 //
4277 // TODO: this runtime "not" for || could be avoided by adding functionality
4278 // to 'builder' to have an "else" without an "then"
4279 if (op == glslang::EOpLogicalOr)
4280 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4281
4282 // make an "if" based on the left value
4283 spv::Builder::If ifBuilder(leftId, builder);
4284
4285 // emit right operand as the "then" part of the "if"
4286 builder.clearAccessChain();
4287 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004288 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004289
4290 // accumulate left operand's phi information
4291 phiOperands.push_back(rightId);
4292 phiOperands.push_back(builder.getBuildPoint()->getId());
4293
4294 // finish the "if"
4295 ifBuilder.makeEndIf();
4296
4297 // phi together the two results
4298 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4299}
4300
John Kessenich140f3df2015-06-26 16:58:36 -06004301}; // end anonymous namespace
4302
4303namespace glslang {
4304
John Kessenich68d78fd2015-07-12 19:28:10 -06004305void GetSpirvVersion(std::string& version)
4306{
John Kessenich9e55f632015-07-15 10:03:39 -06004307 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004308 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004309 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004310 version = buf;
4311}
4312
John Kessenich140f3df2015-06-26 16:58:36 -06004313// Write SPIR-V out to a binary file
4314void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4315{
4316 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004317 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004318 for (int i = 0; i < (int)spirv.size(); ++i) {
4319 unsigned int word = spirv[i];
4320 out.write((const char*)&word, 4);
4321 }
4322 out.close();
4323}
4324
4325//
4326// Set up the glslang traversal
4327//
4328void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4329{
Lei Zhang17535f72016-05-04 15:55:59 -04004330 spv::SpvBuildLogger logger;
4331 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004332}
4333
Lei Zhang17535f72016-05-04 15:55:59 -04004334void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004335{
John Kessenich140f3df2015-06-26 16:58:36 -06004336 TIntermNode* root = intermediate.getTreeRoot();
4337
4338 if (root == 0)
4339 return;
4340
4341 glslang::GetThreadPoolAllocator().push();
4342
Lei Zhang17535f72016-05-04 15:55:59 -04004343 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004344
4345 root->traverse(&it);
4346
4347 it.dumpSpv(spirv);
4348
4349 glslang::GetThreadPoolAllocator().pop();
4350}
4351
4352}; // end namespace glslang