blob: cfbee00f7faef328b71d48dfb8c16b35de5760a7 [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 Kessenicha5c33d62016-06-02 23:45:21 -06002561 // See if the sampler param should really be just the SPV image part
2562 if (cracked.fetch) {
2563 // a fetch needs to have the image extracted first
2564 if (builder.isSampledImage(params.sampler))
2565 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2566 }
2567
John Kessenichfc51d282015-08-19 13:34:18 -06002568 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002569
John Kessenichfc51d282015-08-19 13:34:18 -06002570 params.coords = arguments[1];
2571 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002572 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002573
2574 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002575 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002576 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002577 ++extraArgs;
2578 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002579 params.Dref = arguments[2];
2580 ++extraArgs;
2581 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002582 std::vector<spv::Id> indexes;
2583 int comp;
2584 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002585 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002586 else
2587 comp = builder.getNumComponents(params.coords) - 1;
2588 indexes.push_back(comp);
2589 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2590 }
2591 if (cracked.lod) {
2592 params.lod = arguments[2];
2593 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002594 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2595 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2596 noImplicitLod = true;
2597 }
2598 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002599 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002600 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002601 }
2602 if (cracked.grad) {
2603 params.gradX = arguments[2 + extraArgs];
2604 params.gradY = arguments[3 + extraArgs];
2605 extraArgs += 2;
2606 }
John Kessenich55e7d112015-11-15 21:33:39 -07002607 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002608 params.offset = arguments[2 + extraArgs];
2609 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002610 } else if (cracked.offsets) {
2611 params.offsets = arguments[2 + extraArgs];
2612 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002613 }
Rex Xu48edadf2015-12-31 16:11:41 +08002614 if (cracked.lodClamp) {
2615 params.lodClamp = arguments[2 + extraArgs];
2616 ++extraArgs;
2617 }
2618 if (sparse) {
2619 params.texelOut = arguments[2 + extraArgs];
2620 ++extraArgs;
2621 }
John Kessenichfc51d282015-08-19 13:34:18 -06002622 if (bias) {
2623 params.bias = arguments[2 + extraArgs];
2624 ++extraArgs;
2625 }
John Kessenich55e7d112015-11-15 21:33:39 -07002626 if (cracked.gather && ! sampler.shadow) {
2627 // default component is 0, if missing, otherwise an argument
2628 if (2 + extraArgs < (int)arguments.size()) {
2629 params.comp = arguments[2 + extraArgs];
2630 ++extraArgs;
2631 } else {
2632 params.comp = builder.makeIntConstant(0);
2633 }
2634 }
John Kessenichfc51d282015-08-19 13:34:18 -06002635
John Kessenich019f08f2016-02-15 15:40:42 -07002636 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002637}
2638
2639spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2640{
2641 // Grab the function's pointer from the previously created function
2642 spv::Function* function = functionMap[node->getName().c_str()];
2643 if (! function)
2644 return 0;
2645
2646 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2647 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2648
2649 // See comments in makeFunctions() for details about the semantics for parameter passing.
2650 //
2651 // These imply we need a four step process:
2652 // 1. Evaluate the arguments
2653 // 2. Allocate and make copies of in, out, and inout arguments
2654 // 3. Make the call
2655 // 4. Copy back the results
2656
2657 // 1. Evaluate the arguments
2658 std::vector<spv::Builder::AccessChain> lValues;
2659 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002660 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002661 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002662 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002663 // build l-value
2664 builder.clearAccessChain();
2665 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002666 argTypes.push_back(&paramType);
2667 // keep outputs as and samplers l-values, evaluate input-only as r-values
2668 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.getBasicType() == glslang::EbtSampler) {
John Kessenich140f3df2015-06-26 16:58:36 -06002669 // save l-value
2670 lValues.push_back(builder.getAccessChain());
2671 } else {
2672 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002673 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002674 }
2675 }
2676
2677 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2678 // copy the original into that space.
2679 //
2680 // Also, build up the list of actual arguments to pass in for the call
2681 int lValueCount = 0;
2682 int rValueCount = 0;
2683 std::vector<spv::Id> spvArgs;
2684 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002685 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002686 spv::Id arg;
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002687 if (paramType.getBasicType() == glslang::EbtSampler) {
2688 builder.setAccessChain(lValues[lValueCount]);
2689 arg = builder.accessChainGetLValue();
2690 ++lValueCount;
2691 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002692 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002693 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2694 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2695 // need to copy the input into output space
2696 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002697 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002698 builder.createStore(copy, arg);
2699 }
2700 ++lValueCount;
2701 } else {
2702 arg = rValues[rValueCount];
2703 ++rValueCount;
2704 }
2705 spvArgs.push_back(arg);
2706 }
2707
2708 // 3. Make the call.
2709 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002710 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002711
2712 // 4. Copy back out an "out" arguments.
2713 lValueCount = 0;
2714 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2715 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2716 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2717 spv::Id copy = builder.createLoad(spvArgs[a]);
2718 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002719 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002720 }
2721 ++lValueCount;
2722 }
2723 }
2724
2725 return result;
2726}
2727
2728// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002729spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2730 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002731 spv::Id typeId, spv::Id left, spv::Id right,
2732 glslang::TBasicType typeProxy, bool reduceComparison)
2733{
Rex Xu8ff43de2016-04-22 16:51:45 +08002734 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002735 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002736 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002737
2738 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002739 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002740 bool comparison = false;
2741
2742 switch (op) {
2743 case glslang::EOpAdd:
2744 case glslang::EOpAddAssign:
2745 if (isFloat)
2746 binOp = spv::OpFAdd;
2747 else
2748 binOp = spv::OpIAdd;
2749 break;
2750 case glslang::EOpSub:
2751 case glslang::EOpSubAssign:
2752 if (isFloat)
2753 binOp = spv::OpFSub;
2754 else
2755 binOp = spv::OpISub;
2756 break;
2757 case glslang::EOpMul:
2758 case glslang::EOpMulAssign:
2759 if (isFloat)
2760 binOp = spv::OpFMul;
2761 else
2762 binOp = spv::OpIMul;
2763 break;
2764 case glslang::EOpVectorTimesScalar:
2765 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002766 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002767 if (builder.isVector(right))
2768 std::swap(left, right);
2769 assert(builder.isScalar(right));
2770 needMatchingVectors = false;
2771 binOp = spv::OpVectorTimesScalar;
2772 } else
2773 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002774 break;
2775 case glslang::EOpVectorTimesMatrix:
2776 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002777 binOp = spv::OpVectorTimesMatrix;
2778 break;
2779 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002780 binOp = spv::OpMatrixTimesVector;
2781 break;
2782 case glslang::EOpMatrixTimesScalar:
2783 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002784 binOp = spv::OpMatrixTimesScalar;
2785 break;
2786 case glslang::EOpMatrixTimesMatrix:
2787 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002788 binOp = spv::OpMatrixTimesMatrix;
2789 break;
2790 case glslang::EOpOuterProduct:
2791 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002792 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002793 break;
2794
2795 case glslang::EOpDiv:
2796 case glslang::EOpDivAssign:
2797 if (isFloat)
2798 binOp = spv::OpFDiv;
2799 else if (isUnsigned)
2800 binOp = spv::OpUDiv;
2801 else
2802 binOp = spv::OpSDiv;
2803 break;
2804 case glslang::EOpMod:
2805 case glslang::EOpModAssign:
2806 if (isFloat)
2807 binOp = spv::OpFMod;
2808 else if (isUnsigned)
2809 binOp = spv::OpUMod;
2810 else
2811 binOp = spv::OpSMod;
2812 break;
2813 case glslang::EOpRightShift:
2814 case glslang::EOpRightShiftAssign:
2815 if (isUnsigned)
2816 binOp = spv::OpShiftRightLogical;
2817 else
2818 binOp = spv::OpShiftRightArithmetic;
2819 break;
2820 case glslang::EOpLeftShift:
2821 case glslang::EOpLeftShiftAssign:
2822 binOp = spv::OpShiftLeftLogical;
2823 break;
2824 case glslang::EOpAnd:
2825 case glslang::EOpAndAssign:
2826 binOp = spv::OpBitwiseAnd;
2827 break;
2828 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002829 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002830 binOp = spv::OpLogicalAnd;
2831 break;
2832 case glslang::EOpInclusiveOr:
2833 case glslang::EOpInclusiveOrAssign:
2834 binOp = spv::OpBitwiseOr;
2835 break;
2836 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002837 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002838 binOp = spv::OpLogicalOr;
2839 break;
2840 case glslang::EOpExclusiveOr:
2841 case glslang::EOpExclusiveOrAssign:
2842 binOp = spv::OpBitwiseXor;
2843 break;
2844 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002845 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002846 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002847 break;
2848
2849 case glslang::EOpLessThan:
2850 case glslang::EOpGreaterThan:
2851 case glslang::EOpLessThanEqual:
2852 case glslang::EOpGreaterThanEqual:
2853 case glslang::EOpEqual:
2854 case glslang::EOpNotEqual:
2855 case glslang::EOpVectorEqual:
2856 case glslang::EOpVectorNotEqual:
2857 comparison = true;
2858 break;
2859 default:
2860 break;
2861 }
2862
John Kessenich7c1aa102015-10-15 13:29:11 -06002863 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002864 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002865 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002866 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002867 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002868
2869 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002870 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002871 builder.promoteScalar(precision, left, right);
2872
qining25262b32016-05-06 17:25:16 -04002873 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2874 addDecoration(result, noContraction);
2875 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002876 }
2877
2878 if (! comparison)
2879 return 0;
2880
John Kessenich7c1aa102015-10-15 13:29:11 -06002881 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002882
2883 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2884 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2885
John Kessenich22118352015-12-21 20:54:09 -07002886 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002887 }
2888
2889 switch (op) {
2890 case glslang::EOpLessThan:
2891 if (isFloat)
2892 binOp = spv::OpFOrdLessThan;
2893 else if (isUnsigned)
2894 binOp = spv::OpULessThan;
2895 else
2896 binOp = spv::OpSLessThan;
2897 break;
2898 case glslang::EOpGreaterThan:
2899 if (isFloat)
2900 binOp = spv::OpFOrdGreaterThan;
2901 else if (isUnsigned)
2902 binOp = spv::OpUGreaterThan;
2903 else
2904 binOp = spv::OpSGreaterThan;
2905 break;
2906 case glslang::EOpLessThanEqual:
2907 if (isFloat)
2908 binOp = spv::OpFOrdLessThanEqual;
2909 else if (isUnsigned)
2910 binOp = spv::OpULessThanEqual;
2911 else
2912 binOp = spv::OpSLessThanEqual;
2913 break;
2914 case glslang::EOpGreaterThanEqual:
2915 if (isFloat)
2916 binOp = spv::OpFOrdGreaterThanEqual;
2917 else if (isUnsigned)
2918 binOp = spv::OpUGreaterThanEqual;
2919 else
2920 binOp = spv::OpSGreaterThanEqual;
2921 break;
2922 case glslang::EOpEqual:
2923 case glslang::EOpVectorEqual:
2924 if (isFloat)
2925 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002926 else if (isBool)
2927 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002928 else
2929 binOp = spv::OpIEqual;
2930 break;
2931 case glslang::EOpNotEqual:
2932 case glslang::EOpVectorNotEqual:
2933 if (isFloat)
2934 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002935 else if (isBool)
2936 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 else
2938 binOp = spv::OpINotEqual;
2939 break;
2940 default:
2941 break;
2942 }
2943
qining25262b32016-05-06 17:25:16 -04002944 if (binOp != spv::OpNop) {
2945 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2946 addDecoration(result, noContraction);
2947 return builder.setPrecision(result, precision);
2948 }
John Kessenich140f3df2015-06-26 16:58:36 -06002949
2950 return 0;
2951}
2952
John Kessenich04bb8a02015-12-12 12:28:14 -07002953//
2954// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2955// These can be any of:
2956//
2957// matrix * scalar
2958// scalar * matrix
2959// matrix * matrix linear algebraic
2960// matrix * vector
2961// vector * matrix
2962// matrix * matrix componentwise
2963// matrix op matrix op in {+, -, /}
2964// matrix op scalar op in {+, -, /}
2965// scalar op matrix op in {+, -, /}
2966//
qining25262b32016-05-06 17:25:16 -04002967spv::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 -07002968{
2969 bool firstClass = true;
2970
2971 // First, handle first-class matrix operations (* and matrix/scalar)
2972 switch (op) {
2973 case spv::OpFDiv:
2974 if (builder.isMatrix(left) && builder.isScalar(right)) {
2975 // turn matrix / scalar into a multiply...
2976 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2977 op = spv::OpMatrixTimesScalar;
2978 } else
2979 firstClass = false;
2980 break;
2981 case spv::OpMatrixTimesScalar:
2982 if (builder.isMatrix(right))
2983 std::swap(left, right);
2984 assert(builder.isScalar(right));
2985 break;
2986 case spv::OpVectorTimesMatrix:
2987 assert(builder.isVector(left));
2988 assert(builder.isMatrix(right));
2989 break;
2990 case spv::OpMatrixTimesVector:
2991 assert(builder.isMatrix(left));
2992 assert(builder.isVector(right));
2993 break;
2994 case spv::OpMatrixTimesMatrix:
2995 assert(builder.isMatrix(left));
2996 assert(builder.isMatrix(right));
2997 break;
2998 default:
2999 firstClass = false;
3000 break;
3001 }
3002
qining25262b32016-05-06 17:25:16 -04003003 if (firstClass) {
3004 spv::Id result = builder.createBinOp(op, typeId, left, right);
3005 addDecoration(result, noContraction);
3006 return builder.setPrecision(result, precision);
3007 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003008
3009 // Handle component-wise +, -, *, and / for all combinations of type.
3010 // The result type of all of them is the same type as the (a) matrix operand.
3011 // The algorithm is to:
3012 // - break the matrix(es) into vectors
3013 // - smear any scalar to a vector
3014 // - do vector operations
3015 // - make a matrix out the vector results
3016 switch (op) {
3017 case spv::OpFAdd:
3018 case spv::OpFSub:
3019 case spv::OpFDiv:
3020 case spv::OpFMul:
3021 {
3022 // one time set up...
3023 bool leftMat = builder.isMatrix(left);
3024 bool rightMat = builder.isMatrix(right);
3025 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3026 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3027 spv::Id scalarType = builder.getScalarTypeId(typeId);
3028 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3029 std::vector<spv::Id> results;
3030 spv::Id smearVec = spv::NoResult;
3031 if (builder.isScalar(left))
3032 smearVec = builder.smearScalar(precision, left, vecType);
3033 else if (builder.isScalar(right))
3034 smearVec = builder.smearScalar(precision, right, vecType);
3035
3036 // do each vector op
3037 for (unsigned int c = 0; c < numCols; ++c) {
3038 std::vector<unsigned int> indexes;
3039 indexes.push_back(c);
3040 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3041 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003042 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3043 addDecoration(result, noContraction);
3044 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003045 }
3046
3047 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003048 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003049 }
3050 default:
3051 assert(0);
3052 return spv::NoResult;
3053 }
3054}
3055
qining25262b32016-05-06 17:25:16 -04003056spv::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 -06003057{
3058 spv::Op unaryOp = spv::OpNop;
3059 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003060 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003061 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003062
3063 switch (op) {
3064 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003065 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003066 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003067 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003068 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003069 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003070 unaryOp = spv::OpSNegate;
3071 break;
3072
3073 case glslang::EOpLogicalNot:
3074 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 unaryOp = spv::OpLogicalNot;
3076 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003077 case glslang::EOpBitwiseNot:
3078 unaryOp = spv::OpNot;
3079 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003080
John Kessenich140f3df2015-06-26 16:58:36 -06003081 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003082 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003083 break;
3084 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003086 break;
3087 case glslang::EOpTranspose:
3088 unaryOp = spv::OpTranspose;
3089 break;
3090
3091 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 break;
3100 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003101 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003102 break;
3103 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003104 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003105 break;
3106 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003107 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003108 break;
3109 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003110 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003111 break;
3112 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003114 break;
3115
3116 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134
3135 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003136 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003137 break;
3138 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003139 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003140 break;
3141
3142 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003143 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003144 break;
3145 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003146 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003147 break;
3148 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003149 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003152 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003153 break;
3154 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003155 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160
3161 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003162 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003171 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
3173 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003174 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 break;
3176 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003177 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003178 break;
3179
3180 case glslang::EOpIsNan:
3181 unaryOp = spv::OpIsNan;
3182 break;
3183 case glslang::EOpIsInf:
3184 unaryOp = spv::OpIsInf;
3185 break;
3186
Rex Xucbc426e2015-12-15 16:03:10 +08003187 case glslang::EOpFloatBitsToInt:
3188 case glslang::EOpFloatBitsToUint:
3189 case glslang::EOpIntBitsToFloat:
3190 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003191 case glslang::EOpDoubleBitsToInt64:
3192 case glslang::EOpDoubleBitsToUint64:
3193 case glslang::EOpInt64BitsToDouble:
3194 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003195 unaryOp = spv::OpBitcast;
3196 break;
3197
John Kessenich140f3df2015-06-26 16:58:36 -06003198 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003200 break;
3201 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003202 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 break;
3204 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003205 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003206 break;
3207 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003208 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003209 break;
3210 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003211 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003212 break;
3213 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003214 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003215 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003216 case glslang::EOpPackSnorm4x8:
3217 libCall = spv::GLSLstd450PackSnorm4x8;
3218 break;
3219 case glslang::EOpUnpackSnorm4x8:
3220 libCall = spv::GLSLstd450UnpackSnorm4x8;
3221 break;
3222 case glslang::EOpPackUnorm4x8:
3223 libCall = spv::GLSLstd450PackUnorm4x8;
3224 break;
3225 case glslang::EOpUnpackUnorm4x8:
3226 libCall = spv::GLSLstd450UnpackUnorm4x8;
3227 break;
3228 case glslang::EOpPackDouble2x32:
3229 libCall = spv::GLSLstd450PackDouble2x32;
3230 break;
3231 case glslang::EOpUnpackDouble2x32:
3232 libCall = spv::GLSLstd450UnpackDouble2x32;
3233 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003234
Rex Xu8ff43de2016-04-22 16:51:45 +08003235 case glslang::EOpPackInt2x32:
3236 case glslang::EOpUnpackInt2x32:
3237 case glslang::EOpPackUint2x32:
3238 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003239 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003240 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3241 break;
3242
John Kessenich140f3df2015-06-26 16:58:36 -06003243 case glslang::EOpDPdx:
3244 unaryOp = spv::OpDPdx;
3245 break;
3246 case glslang::EOpDPdy:
3247 unaryOp = spv::OpDPdy;
3248 break;
3249 case glslang::EOpFwidth:
3250 unaryOp = spv::OpFwidth;
3251 break;
3252 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003253 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003254 unaryOp = spv::OpDPdxFine;
3255 break;
3256 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003257 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003258 unaryOp = spv::OpDPdyFine;
3259 break;
3260 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003261 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 unaryOp = spv::OpFwidthFine;
3263 break;
3264 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003265 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003266 unaryOp = spv::OpDPdxCoarse;
3267 break;
3268 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003269 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003270 unaryOp = spv::OpDPdyCoarse;
3271 break;
3272 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003273 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003274 unaryOp = spv::OpFwidthCoarse;
3275 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003276 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003277 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003278 libCall = spv::GLSLstd450InterpolateAtCentroid;
3279 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 case glslang::EOpAny:
3281 unaryOp = spv::OpAny;
3282 break;
3283 case glslang::EOpAll:
3284 unaryOp = spv::OpAll;
3285 break;
3286
3287 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003288 if (isFloat)
3289 libCall = spv::GLSLstd450FAbs;
3290 else
3291 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003292 break;
3293 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003294 if (isFloat)
3295 libCall = spv::GLSLstd450FSign;
3296 else
3297 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003298 break;
3299
John Kessenichfc51d282015-08-19 13:34:18 -06003300 case glslang::EOpAtomicCounterIncrement:
3301 case glslang::EOpAtomicCounterDecrement:
3302 case glslang::EOpAtomicCounter:
3303 {
3304 // Handle all of the atomics in one place, in createAtomicOperation()
3305 std::vector<spv::Id> operands;
3306 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003307 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003308 }
3309
John Kessenichfc51d282015-08-19 13:34:18 -06003310 case glslang::EOpBitFieldReverse:
3311 unaryOp = spv::OpBitReverse;
3312 break;
3313 case glslang::EOpBitCount:
3314 unaryOp = spv::OpBitCount;
3315 break;
3316 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003317 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003318 break;
3319 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003320 if (isUnsigned)
3321 libCall = spv::GLSLstd450FindUMsb;
3322 else
3323 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003324 break;
3325
Rex Xu574ab042016-04-14 16:53:07 +08003326 case glslang::EOpBallot:
3327 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003328 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003329 libCall = spv::GLSLstd450Bad;
3330 break;
3331
Rex Xu338b1852016-05-05 20:38:33 +08003332 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003333 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003334 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003335 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003336
John Kessenich140f3df2015-06-26 16:58:36 -06003337 default:
3338 return 0;
3339 }
3340
3341 spv::Id id;
3342 if (libCall >= 0) {
3343 std::vector<spv::Id> args;
3344 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003345 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003346 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003347 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003348 }
John Kessenich140f3df2015-06-26 16:58:36 -06003349
qining25262b32016-05-06 17:25:16 -04003350 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003351 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003352}
3353
John Kessenich7a53f762016-01-20 11:19:27 -07003354// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003355spv::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 -07003356{
3357 // Handle unary operations vector by vector.
3358 // The result type is the same type as the original type.
3359 // The algorithm is to:
3360 // - break the matrix into vectors
3361 // - apply the operation to each vector
3362 // - make a matrix out the vector results
3363
3364 // get the types sorted out
3365 int numCols = builder.getNumColumns(operand);
3366 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003367 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3368 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003369 std::vector<spv::Id> results;
3370
3371 // do each vector op
3372 for (int c = 0; c < numCols; ++c) {
3373 std::vector<unsigned int> indexes;
3374 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003375 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3376 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3377 addDecoration(destVec, noContraction);
3378 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003379 }
3380
3381 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003382 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003383}
3384
Rex Xu73e3ce72016-04-27 18:48:17 +08003385spv::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 -06003386{
3387 spv::Op convOp = spv::OpNop;
3388 spv::Id zero = 0;
3389 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003390 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003391
3392 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3393
3394 switch (op) {
3395 case glslang::EOpConvIntToBool:
3396 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003397 case glslang::EOpConvInt64ToBool:
3398 case glslang::EOpConvUint64ToBool:
3399 zero = (op == glslang::EOpConvInt64ToBool ||
3400 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003401 zero = makeSmearedConstant(zero, vectorSize);
3402 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3403
3404 case glslang::EOpConvFloatToBool:
3405 zero = builder.makeFloatConstant(0.0F);
3406 zero = makeSmearedConstant(zero, vectorSize);
3407 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3408
3409 case glslang::EOpConvDoubleToBool:
3410 zero = builder.makeDoubleConstant(0.0);
3411 zero = makeSmearedConstant(zero, vectorSize);
3412 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3413
3414 case glslang::EOpConvBoolToFloat:
3415 convOp = spv::OpSelect;
3416 zero = builder.makeFloatConstant(0.0);
3417 one = builder.makeFloatConstant(1.0);
3418 break;
3419 case glslang::EOpConvBoolToDouble:
3420 convOp = spv::OpSelect;
3421 zero = builder.makeDoubleConstant(0.0);
3422 one = builder.makeDoubleConstant(1.0);
3423 break;
3424 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003425 case glslang::EOpConvBoolToInt64:
3426 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3427 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003428 convOp = spv::OpSelect;
3429 break;
3430 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003431 case glslang::EOpConvBoolToUint64:
3432 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3433 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003434 convOp = spv::OpSelect;
3435 break;
3436
3437 case glslang::EOpConvIntToFloat:
3438 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003439 case glslang::EOpConvInt64ToFloat:
3440 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003441 convOp = spv::OpConvertSToF;
3442 break;
3443
3444 case glslang::EOpConvUintToFloat:
3445 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003446 case glslang::EOpConvUint64ToFloat:
3447 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003448 convOp = spv::OpConvertUToF;
3449 break;
3450
3451 case glslang::EOpConvDoubleToFloat:
3452 case glslang::EOpConvFloatToDouble:
3453 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003454 if (builder.isMatrixType(destType))
3455 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003456 break;
3457
3458 case glslang::EOpConvFloatToInt:
3459 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003460 case glslang::EOpConvFloatToInt64:
3461 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003462 convOp = spv::OpConvertFToS;
3463 break;
3464
3465 case glslang::EOpConvUintToInt:
3466 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003467 case glslang::EOpConvUint64ToInt64:
3468 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003469 if (builder.isInSpecConstCodeGenMode()) {
3470 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003471 zero = (op == glslang::EOpConvUintToInt64 ||
3472 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003473 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003474 // Use OpIAdd, instead of OpBitcast to do the conversion when
3475 // generating for OpSpecConstantOp instruction.
3476 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3477 }
3478 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003479 convOp = spv::OpBitcast;
3480 break;
3481
3482 case glslang::EOpConvFloatToUint:
3483 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003484 case glslang::EOpConvFloatToUint64:
3485 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003486 convOp = spv::OpConvertFToU;
3487 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003488
3489 case glslang::EOpConvIntToInt64:
3490 case glslang::EOpConvInt64ToInt:
3491 convOp = spv::OpSConvert;
3492 break;
3493
3494 case glslang::EOpConvUintToUint64:
3495 case glslang::EOpConvUint64ToUint:
3496 convOp = spv::OpUConvert;
3497 break;
3498
3499 case glslang::EOpConvIntToUint64:
3500 case glslang::EOpConvInt64ToUint:
3501 case glslang::EOpConvUint64ToInt:
3502 case glslang::EOpConvUintToInt64:
3503 // OpSConvert/OpUConvert + OpBitCast
3504 switch (op) {
3505 case glslang::EOpConvIntToUint64:
3506 convOp = spv::OpSConvert;
3507 type = builder.makeIntType(64);
3508 break;
3509 case glslang::EOpConvInt64ToUint:
3510 convOp = spv::OpSConvert;
3511 type = builder.makeIntType(32);
3512 break;
3513 case glslang::EOpConvUint64ToInt:
3514 convOp = spv::OpUConvert;
3515 type = builder.makeUintType(32);
3516 break;
3517 case glslang::EOpConvUintToInt64:
3518 convOp = spv::OpUConvert;
3519 type = builder.makeUintType(64);
3520 break;
3521 default:
3522 assert(0);
3523 break;
3524 }
3525
3526 if (vectorSize > 0)
3527 type = builder.makeVectorType(type, vectorSize);
3528
3529 operand = builder.createUnaryOp(convOp, type, operand);
3530
3531 if (builder.isInSpecConstCodeGenMode()) {
3532 // Build zero scalar or vector for OpIAdd.
3533 zero = (op == glslang::EOpConvIntToUint64 ||
3534 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3535 zero = makeSmearedConstant(zero, vectorSize);
3536 // Use OpIAdd, instead of OpBitcast to do the conversion when
3537 // generating for OpSpecConstantOp instruction.
3538 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3539 }
3540 // For normal run-time conversion instruction, use OpBitcast.
3541 convOp = spv::OpBitcast;
3542 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003543 default:
3544 break;
3545 }
3546
3547 spv::Id result = 0;
3548 if (convOp == spv::OpNop)
3549 return result;
3550
3551 if (convOp == spv::OpSelect) {
3552 zero = makeSmearedConstant(zero, vectorSize);
3553 one = makeSmearedConstant(one, vectorSize);
3554 result = builder.createTriOp(convOp, destType, operand, one, zero);
3555 } else
3556 result = builder.createUnaryOp(convOp, destType, operand);
3557
John Kessenich32cfd492016-02-02 12:37:46 -07003558 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003559}
3560
3561spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3562{
3563 if (vectorSize == 0)
3564 return constant;
3565
3566 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3567 std::vector<spv::Id> components;
3568 for (int c = 0; c < vectorSize; ++c)
3569 components.push_back(constant);
3570 return builder.makeCompositeConstant(vectorTypeId, components);
3571}
3572
John Kessenich426394d2015-07-23 10:22:48 -06003573// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003574spv::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 -06003575{
3576 spv::Op opCode = spv::OpNop;
3577
3578 switch (op) {
3579 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003580 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003581 opCode = spv::OpAtomicIAdd;
3582 break;
3583 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003584 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003585 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003586 break;
3587 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003588 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003589 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003590 break;
3591 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003592 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003593 opCode = spv::OpAtomicAnd;
3594 break;
3595 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003596 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003597 opCode = spv::OpAtomicOr;
3598 break;
3599 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003600 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003601 opCode = spv::OpAtomicXor;
3602 break;
3603 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003604 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003605 opCode = spv::OpAtomicExchange;
3606 break;
3607 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003608 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003609 opCode = spv::OpAtomicCompareExchange;
3610 break;
3611 case glslang::EOpAtomicCounterIncrement:
3612 opCode = spv::OpAtomicIIncrement;
3613 break;
3614 case glslang::EOpAtomicCounterDecrement:
3615 opCode = spv::OpAtomicIDecrement;
3616 break;
3617 case glslang::EOpAtomicCounter:
3618 opCode = spv::OpAtomicLoad;
3619 break;
3620 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003621 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003622 break;
3623 }
3624
3625 // Sort out the operands
3626 // - mapping from glslang -> SPV
3627 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003628 // - compare-exchange swaps the value and comparator
3629 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003630 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3631 auto opIt = operands.begin(); // walk the glslang operands
3632 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003633 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3634 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3635 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003636 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3637 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003638 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003639 spvAtomicOperands.push_back(*(opIt + 1));
3640 spvAtomicOperands.push_back(*opIt);
3641 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003642 }
John Kessenich426394d2015-07-23 10:22:48 -06003643
John Kessenich3e60a6f2015-09-14 22:45:16 -06003644 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003645 for (; opIt != operands.end(); ++opIt)
3646 spvAtomicOperands.push_back(*opIt);
3647
3648 return builder.createOp(opCode, typeId, spvAtomicOperands);
3649}
3650
John Kessenich91cef522016-05-05 16:45:40 -06003651// Create group invocation operations.
3652spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3653{
3654 builder.addCapability(spv::CapabilityGroups);
3655
3656 std::vector<spv::Id> operands;
3657 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3658 operands.push_back(operand);
3659
3660 switch (op) {
3661 case glslang::EOpAnyInvocation:
3662 case glslang::EOpAllInvocations:
3663 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3664
3665 case glslang::EOpAllInvocationsEqual:
3666 {
3667 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3668 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3669
3670 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3671 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3672 }
3673 default:
3674 logger->missingFunctionality("invocation operation");
3675 return spv::NoResult;
3676 }
3677}
3678
John Kessenich5e4b1242015-08-06 22:53:06 -06003679spv::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 -06003680{
Rex Xu8ff43de2016-04-22 16:51:45 +08003681 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003682 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3683
John Kessenich140f3df2015-06-26 16:58:36 -06003684 spv::Op opCode = spv::OpNop;
3685 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003686 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003687 spv::Id typeId0 = 0;
3688 if (consumedOperands > 0)
3689 typeId0 = builder.getTypeId(operands[0]);
3690 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003691
3692 switch (op) {
3693 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003694 if (isFloat)
3695 libCall = spv::GLSLstd450FMin;
3696 else if (isUnsigned)
3697 libCall = spv::GLSLstd450UMin;
3698 else
3699 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003700 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003703 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 break;
3705 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003706 if (isFloat)
3707 libCall = spv::GLSLstd450FMax;
3708 else if (isUnsigned)
3709 libCall = spv::GLSLstd450UMax;
3710 else
3711 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003712 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpDot:
3718 opCode = spv::OpDot;
3719 break;
3720 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723
3724 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 if (isFloat)
3726 libCall = spv::GLSLstd450FClamp;
3727 else if (isUnsigned)
3728 libCall = spv::GLSLstd450UClamp;
3729 else
3730 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003731 builder.promoteScalar(precision, operands.front(), operands[1]);
3732 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
3734 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003735 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3736 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003737 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003738 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003739 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003740 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003741 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003742 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
3744 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003746 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
3748 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003749 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003750 builder.promoteScalar(precision, operands[0], operands[2]);
3751 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753
3754 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003769 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003770 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003771 libCall = spv::GLSLstd450InterpolateAtSample;
3772 break;
3773 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003774 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003775 libCall = spv::GLSLstd450InterpolateAtOffset;
3776 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003777 case glslang::EOpAddCarry:
3778 opCode = spv::OpIAddCarry;
3779 typeId = builder.makeStructResultType(typeId0, typeId0);
3780 consumedOperands = 2;
3781 break;
3782 case glslang::EOpSubBorrow:
3783 opCode = spv::OpISubBorrow;
3784 typeId = builder.makeStructResultType(typeId0, typeId0);
3785 consumedOperands = 2;
3786 break;
3787 case glslang::EOpUMulExtended:
3788 opCode = spv::OpUMulExtended;
3789 typeId = builder.makeStructResultType(typeId0, typeId0);
3790 consumedOperands = 2;
3791 break;
3792 case glslang::EOpIMulExtended:
3793 opCode = spv::OpSMulExtended;
3794 typeId = builder.makeStructResultType(typeId0, typeId0);
3795 consumedOperands = 2;
3796 break;
3797 case glslang::EOpBitfieldExtract:
3798 if (isUnsigned)
3799 opCode = spv::OpBitFieldUExtract;
3800 else
3801 opCode = spv::OpBitFieldSExtract;
3802 break;
3803 case glslang::EOpBitfieldInsert:
3804 opCode = spv::OpBitFieldInsert;
3805 break;
3806
3807 case glslang::EOpFma:
3808 libCall = spv::GLSLstd450Fma;
3809 break;
3810 case glslang::EOpFrexp:
3811 libCall = spv::GLSLstd450FrexpStruct;
3812 if (builder.getNumComponents(operands[0]) == 1)
3813 frexpIntType = builder.makeIntegerType(32, true);
3814 else
3815 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3816 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3817 consumedOperands = 1;
3818 break;
3819 case glslang::EOpLdexp:
3820 libCall = spv::GLSLstd450Ldexp;
3821 break;
3822
Rex Xu574ab042016-04-14 16:53:07 +08003823 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003824 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003825 libCall = spv::GLSLstd450Bad;
3826 break;
3827
John Kessenich140f3df2015-06-26 16:58:36 -06003828 default:
3829 return 0;
3830 }
3831
3832 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003833 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003834 // Use an extended instruction from the standard library.
3835 // Construct the call arguments, without modifying the original operands vector.
3836 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3837 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003838 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003839 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003840 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003841 case 0:
3842 // should all be handled by visitAggregate and createNoArgOperation
3843 assert(0);
3844 return 0;
3845 case 1:
3846 // should all be handled by createUnaryOperation
3847 assert(0);
3848 return 0;
3849 case 2:
3850 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3851 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003853 // anything 3 or over doesn't have l-value operands, so all should be consumed
3854 assert(consumedOperands == operands.size());
3855 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857 }
3858 }
3859
John Kessenich55e7d112015-11-15 21:33:39 -07003860 // Decode the return types that were structures
3861 switch (op) {
3862 case glslang::EOpAddCarry:
3863 case glslang::EOpSubBorrow:
3864 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3865 id = builder.createCompositeExtract(id, typeId0, 0);
3866 break;
3867 case glslang::EOpUMulExtended:
3868 case glslang::EOpIMulExtended:
3869 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3870 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3871 break;
3872 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003873 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003874 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3875 id = builder.createCompositeExtract(id, typeId0, 0);
3876 break;
3877 default:
3878 break;
3879 }
3880
John Kessenich32cfd492016-02-02 12:37:46 -07003881 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003882}
3883
3884// Intrinsics with no arguments, no return value, and no precision.
3885spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3886{
3887 // TODO: get the barrier operands correct
3888
3889 switch (op) {
3890 case glslang::EOpEmitVertex:
3891 builder.createNoResultOp(spv::OpEmitVertex);
3892 return 0;
3893 case glslang::EOpEndPrimitive:
3894 builder.createNoResultOp(spv::OpEndPrimitive);
3895 return 0;
3896 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003897 if (glslangIntermediate->getProfile() != EEsProfile)
3898 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003899 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003900 return 0;
3901 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003902 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003903 return 0;
3904 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003905 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003906 return 0;
3907 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003908 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003909 return 0;
3910 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003912 return 0;
3913 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003914 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003915 return 0;
3916 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003917 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003918 return 0;
3919 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003920 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003921 return 0;
3922 }
3923}
3924
3925spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3926{
John Kessenich2f273362015-07-18 22:34:27 -06003927 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003928 spv::Id id;
3929 if (symbolValues.end() != iter) {
3930 id = iter->second;
3931 return id;
3932 }
3933
3934 // it was not found, create it
3935 id = createSpvVariable(symbol);
3936 symbolValues[symbol->getId()] = id;
3937
3938 if (! symbol->getType().isStruct()) {
3939 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003940 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003941 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003942 if (symbol->getType().getQualifier().hasSpecConstantId())
3943 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003944 if (symbol->getQualifier().hasIndex())
3945 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3946 if (symbol->getQualifier().hasComponent())
3947 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3948 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003949 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003950 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003951 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003952 if (symbol->getQualifier().hasXfbBuffer())
3953 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3954 if (symbol->getQualifier().hasXfbOffset())
3955 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3956 }
3957 }
3958
scygan2c864272016-05-18 18:09:17 +02003959 if (symbol->getQualifier().hasLocation())
3960 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003961 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003962 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003963 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003964 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003965 }
John Kessenich140f3df2015-06-26 16:58:36 -06003966 if (symbol->getQualifier().hasSet())
3967 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003968 else if (IsDescriptorResource(symbol->getType())) {
3969 // default to 0
3970 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3971 }
John Kessenich140f3df2015-06-26 16:58:36 -06003972 if (symbol->getQualifier().hasBinding())
3973 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003974 if (symbol->getQualifier().hasAttachment())
3975 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003976 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003977 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003978 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003980 if (symbol->getQualifier().hasXfbBuffer())
3981 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3982 }
3983
Rex Xu1da878f2016-02-21 20:59:01 +08003984 if (symbol->getType().isImage()) {
3985 std::vector<spv::Decoration> memory;
3986 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3987 for (unsigned int i = 0; i < memory.size(); ++i)
3988 addDecoration(id, memory[i]);
3989 }
3990
John Kessenich140f3df2015-06-26 16:58:36 -06003991 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003992 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003993 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003994 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003995
John Kessenich140f3df2015-06-26 16:58:36 -06003996 return id;
3997}
3998
John Kessenich55e7d112015-11-15 21:33:39 -07003999// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004000void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4001{
4002 if (dec != spv::BadValue)
4003 builder.addDecoration(id, dec);
4004}
4005
John Kessenich55e7d112015-11-15 21:33:39 -07004006// If 'dec' is valid, add a one-operand decoration to an object
4007void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4008{
4009 if (dec != spv::BadValue)
4010 builder.addDecoration(id, dec, value);
4011}
4012
4013// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004014void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4015{
4016 if (dec != spv::BadValue)
4017 builder.addMemberDecoration(id, (unsigned)member, dec);
4018}
4019
John Kessenich92187592016-02-01 13:45:25 -07004020// If 'dec' is valid, add a one-operand decoration to a struct member
4021void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4022{
4023 if (dec != spv::BadValue)
4024 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4025}
4026
John Kessenich55e7d112015-11-15 21:33:39 -07004027// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004028// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004029//
4030// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4031//
4032// Recursively walk the nodes. The nodes form a tree whose leaves are
4033// regular constants, which themselves are trees that createSpvConstant()
4034// recursively walks. So, this function walks the "top" of the tree:
4035// - emit specialization constant-building instructions for specConstant
4036// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004037spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004038{
John Kessenich7cc0e282016-03-20 00:46:02 -06004039 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004040
qining4f4bb812016-04-03 23:55:17 -04004041 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004042 if (! node.getQualifier().specConstant) {
4043 // hand off to the non-spec-constant path
4044 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4045 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004046 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004047 nextConst, false);
4048 }
4049
4050 // We now know we have a specialization constant to build
4051
John Kessenichd94c0032016-05-30 19:29:40 -06004052 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004053 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4054 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4055 std::vector<spv::Id> dimConstId;
4056 for (int dim = 0; dim < 3; ++dim) {
4057 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4058 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4059 if (specConst)
4060 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4061 }
4062 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4063 }
4064
4065 // An AST node labelled as specialization constant should be a symbol node.
4066 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4067 if (auto* sn = node.getAsSymbolNode()) {
4068 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004069 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4070 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4071 // will set the builder into spec constant op instruction generating mode.
4072 sub_tree->traverse(this);
4073 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004074 } else if (auto* const_union_array = &sn->getConstArray()){
4075 int nextConst = 0;
4076 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004077 }
4078 }
qining4f4bb812016-04-03 23:55:17 -04004079
4080 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4081 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004082 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004083 exit(1);
4084 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004085}
4086
John Kessenich140f3df2015-06-26 16:58:36 -06004087// Use 'consts' as the flattened glslang source of scalar constants to recursively
4088// build the aggregate SPIR-V constant.
4089//
4090// If there are not enough elements present in 'consts', 0 will be substituted;
4091// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4092//
qining08408382016-03-21 09:51:37 -04004093spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004094{
4095 // vector of constants for SPIR-V
4096 std::vector<spv::Id> spvConsts;
4097
4098 // Type is used for struct and array constants
4099 spv::Id typeId = convertGlslangToSpvType(glslangType);
4100
4101 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004102 glslang::TType elementType(glslangType, 0);
4103 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004104 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004105 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004106 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004107 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004108 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004109 } else if (glslangType.getStruct()) {
4110 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4111 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004112 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004113 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004114 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4115 bool zero = nextConst >= consts.size();
4116 switch (glslangType.getBasicType()) {
4117 case glslang::EbtInt:
4118 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4119 break;
4120 case glslang::EbtUint:
4121 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4122 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004123 case glslang::EbtInt64:
4124 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4125 break;
4126 case glslang::EbtUint64:
4127 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4128 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004129 case glslang::EbtFloat:
4130 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4131 break;
4132 case glslang::EbtDouble:
4133 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4134 break;
4135 case glslang::EbtBool:
4136 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4137 break;
4138 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004139 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 }
4142 ++nextConst;
4143 }
4144 } else {
4145 // we have a non-aggregate (scalar) constant
4146 bool zero = nextConst >= consts.size();
4147 spv::Id scalar = 0;
4148 switch (glslangType.getBasicType()) {
4149 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004150 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004151 break;
4152 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004153 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004154 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004155 case glslang::EbtInt64:
4156 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4157 break;
4158 case glslang::EbtUint64:
4159 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4160 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004161 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004162 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004163 break;
4164 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004165 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004166 break;
4167 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004168 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004169 break;
4170 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004171 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004172 break;
4173 }
4174 ++nextConst;
4175 return scalar;
4176 }
4177
4178 return builder.makeCompositeConstant(typeId, spvConsts);
4179}
4180
John Kessenich7c1aa102015-10-15 13:29:11 -06004181// Return true if the node is a constant or symbol whose reading has no
4182// non-trivial observable cost or effect.
4183bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4184{
4185 // don't know what this is
4186 if (node == nullptr)
4187 return false;
4188
4189 // a constant is safe
4190 if (node->getAsConstantUnion() != nullptr)
4191 return true;
4192
4193 // not a symbol means non-trivial
4194 if (node->getAsSymbolNode() == nullptr)
4195 return false;
4196
4197 // a symbol, depends on what's being read
4198 switch (node->getType().getQualifier().storage) {
4199 case glslang::EvqTemporary:
4200 case glslang::EvqGlobal:
4201 case glslang::EvqIn:
4202 case glslang::EvqInOut:
4203 case glslang::EvqConst:
4204 case glslang::EvqConstReadOnly:
4205 case glslang::EvqUniform:
4206 return true;
4207 default:
4208 return false;
4209 }
qining25262b32016-05-06 17:25:16 -04004210}
John Kessenich7c1aa102015-10-15 13:29:11 -06004211
4212// A node is trivial if it is a single operation with no side effects.
4213// Error on the side of saying non-trivial.
4214// Return true if trivial.
4215bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4216{
4217 if (node == nullptr)
4218 return false;
4219
4220 // symbols and constants are trivial
4221 if (isTrivialLeaf(node))
4222 return true;
4223
4224 // otherwise, it needs to be a simple operation or one or two leaf nodes
4225
4226 // not a simple operation
4227 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4228 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4229 if (binaryNode == nullptr && unaryNode == nullptr)
4230 return false;
4231
4232 // not on leaf nodes
4233 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4234 return false;
4235
4236 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4237 return false;
4238 }
4239
4240 switch (node->getAsOperator()->getOp()) {
4241 case glslang::EOpLogicalNot:
4242 case glslang::EOpConvIntToBool:
4243 case glslang::EOpConvUintToBool:
4244 case glslang::EOpConvFloatToBool:
4245 case glslang::EOpConvDoubleToBool:
4246 case glslang::EOpEqual:
4247 case glslang::EOpNotEqual:
4248 case glslang::EOpLessThan:
4249 case glslang::EOpGreaterThan:
4250 case glslang::EOpLessThanEqual:
4251 case glslang::EOpGreaterThanEqual:
4252 case glslang::EOpIndexDirect:
4253 case glslang::EOpIndexDirectStruct:
4254 case glslang::EOpLogicalXor:
4255 case glslang::EOpAny:
4256 case glslang::EOpAll:
4257 return true;
4258 default:
4259 return false;
4260 }
4261}
4262
4263// Emit short-circuiting code, where 'right' is never evaluated unless
4264// the left side is true (for &&) or false (for ||).
4265spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4266{
4267 spv::Id boolTypeId = builder.makeBoolType();
4268
4269 // emit left operand
4270 builder.clearAccessChain();
4271 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004272 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004273
4274 // Operands to accumulate OpPhi operands
4275 std::vector<spv::Id> phiOperands;
4276 // accumulate left operand's phi information
4277 phiOperands.push_back(leftId);
4278 phiOperands.push_back(builder.getBuildPoint()->getId());
4279
4280 // Make the two kinds of operation symmetric with a "!"
4281 // || => emit "if (! left) result = right"
4282 // && => emit "if ( left) result = right"
4283 //
4284 // TODO: this runtime "not" for || could be avoided by adding functionality
4285 // to 'builder' to have an "else" without an "then"
4286 if (op == glslang::EOpLogicalOr)
4287 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4288
4289 // make an "if" based on the left value
4290 spv::Builder::If ifBuilder(leftId, builder);
4291
4292 // emit right operand as the "then" part of the "if"
4293 builder.clearAccessChain();
4294 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004295 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004296
4297 // accumulate left operand's phi information
4298 phiOperands.push_back(rightId);
4299 phiOperands.push_back(builder.getBuildPoint()->getId());
4300
4301 // finish the "if"
4302 ifBuilder.makeEndIf();
4303
4304 // phi together the two results
4305 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4306}
4307
John Kessenich140f3df2015-06-26 16:58:36 -06004308}; // end anonymous namespace
4309
4310namespace glslang {
4311
John Kessenich68d78fd2015-07-12 19:28:10 -06004312void GetSpirvVersion(std::string& version)
4313{
John Kessenich9e55f632015-07-15 10:03:39 -06004314 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004315 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004316 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004317 version = buf;
4318}
4319
John Kessenich140f3df2015-06-26 16:58:36 -06004320// Write SPIR-V out to a binary file
4321void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4322{
4323 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004324 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004325 for (int i = 0; i < (int)spirv.size(); ++i) {
4326 unsigned int word = spirv[i];
4327 out.write((const char*)&word, 4);
4328 }
4329 out.close();
4330}
4331
4332//
4333// Set up the glslang traversal
4334//
4335void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4336{
Lei Zhang17535f72016-05-04 15:55:59 -04004337 spv::SpvBuildLogger logger;
4338 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004339}
4340
Lei Zhang17535f72016-05-04 15:55:59 -04004341void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004342{
John Kessenich140f3df2015-06-26 16:58:36 -06004343 TIntermNode* root = intermediate.getTreeRoot();
4344
4345 if (root == 0)
4346 return;
4347
4348 glslang::GetThreadPoolAllocator().push();
4349
Lei Zhang17535f72016-05-04 15:55:59 -04004350 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004351
4352 root->traverse(&it);
4353
4354 it.dumpSpv(spirv);
4355
4356 glslang::GetThreadPoolAllocator().pop();
4357}
4358
4359}; // end namespace glslang