blob: de87763a70044baf13b97c51f089b8ab588b28e0 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
46}
John Kessenich140f3df2015-06-26 16:58:36 -060047
48// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020049#include "../glslang/MachineIndependent/localintermediate.h"
50#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060052
John Kessenich140f3df2015-06-26 16:58:36 -060053#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040054#include <list>
55#include <map>
56#include <stack>
57#include <string>
58#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060059
60namespace {
61
John Kessenich55e7d112015-11-15 21:33:39 -070062// For low-order part of the generator's magic number. Bump up
63// when there is a change in the style (e.g., if SSA form changes,
64// or a different instruction sequence to do something gets used).
65const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060066
qining4c912612016-04-01 10:35:16 -040067namespace {
68class SpecConstantOpModeGuard {
69public:
70 SpecConstantOpModeGuard(spv::Builder* builder)
71 : builder_(builder) {
72 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040073 }
74 ~SpecConstantOpModeGuard() {
75 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
76 : builder_->setToNormalCodeGenMode();
77 }
qining40887662016-04-03 22:20:42 -040078 void turnOnSpecConstantOpMode() {
79 builder_->setToSpecConstCodeGenMode();
80 }
qining4c912612016-04-01 10:35:16 -040081
82private:
83 spv::Builder* builder_;
84 bool previous_flag_;
85};
86}
87
John Kessenich140f3df2015-06-26 16:58:36 -060088//
89// The main holder of information for translating glslang to SPIR-V.
90//
91// Derives from the AST walking base class.
92//
93class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
94public:
Lei Zhang17535f72016-05-04 15:55:59 -040095 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060096 virtual ~TGlslangToSpvTraverser();
97
98 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
99 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
100 void visitConstantUnion(glslang::TIntermConstantUnion*);
101 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
102 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
103 void visitSymbol(glslang::TIntermSymbol* symbol);
104 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
105 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
106 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
107
John Kessenich7ba63412015-12-20 17:37:07 -0700108 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110protected:
Rex Xubbceed72016-05-21 09:40:44 +0800111 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600118 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
119 glslang::TLayoutPacking, const glslang::TQualifier&);
120 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
121 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700122 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700123 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800124 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700125 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700126 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
127 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
128 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100129 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600130
131 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
132 void makeFunctions(const glslang::TIntermSequence&);
133 void makeGlobalInitializers(const glslang::TIntermSequence&);
134 void visitFunctions(const glslang::TIntermSequence&);
135 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800136 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600137 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
138 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
140
qining25262b32016-05-06 17:25:16 -0400141 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);
142 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
143 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
144 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 +0800145 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 -0600146 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800147 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 -0600148 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600149 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 -0600150 spv::Id createNoArgOperation(glslang::TOperator op);
151 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
152 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700153 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700155 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400156 spv::Id createSpvConstant(const glslang::TIntermTyped&);
157 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600158 bool isTrivialLeaf(const glslang::TIntermTyped* node);
159 bool isTrivial(const glslang::TIntermTyped* node);
160 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600161
162 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700163 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600164 int sequenceDepth;
165
Lei Zhang17535f72016-05-04 15:55:59 -0400166 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400167
John Kessenich140f3df2015-06-26 16:58:36 -0600168 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
169 spv::Builder builder;
170 bool inMain;
171 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700172 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 -0700173 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600174 const glslang::TIntermediate* glslangIntermediate;
175 spv::Id stdBuiltins;
176
John Kessenich2f273362015-07-18 22:34:27 -0600177 std::unordered_map<int, spv::Id> symbolValues;
178 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
179 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700180 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600181 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 -0600182 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600183};
184
185//
186// Helper functions for translating glslang representations to SPIR-V enumerants.
187//
188
189// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700190spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600191{
John Kessenich66e2faf2016-03-12 18:34:36 -0700192 switch (source) {
193 case glslang::EShSourceGlsl:
194 switch (profile) {
195 case ENoProfile:
196 case ECoreProfile:
197 case ECompatibilityProfile:
198 return spv::SourceLanguageGLSL;
199 case EEsProfile:
200 return spv::SourceLanguageESSL;
201 default:
202 return spv::SourceLanguageUnknown;
203 }
204 case glslang::EShSourceHlsl:
205 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 default:
207 return spv::SourceLanguageUnknown;
208 }
209}
210
211// Translate glslang language (stage) to SPIR-V execution model.
212spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
213{
214 switch (stage) {
215 case EShLangVertex: return spv::ExecutionModelVertex;
216 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
217 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
218 case EShLangGeometry: return spv::ExecutionModelGeometry;
219 case EShLangFragment: return spv::ExecutionModelFragment;
220 case EShLangCompute: return spv::ExecutionModelGLCompute;
221 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600223 return spv::ExecutionModelFragment;
224 }
225}
226
227// Translate glslang type to SPIR-V storage class.
228spv::StorageClass TranslateStorageClass(const glslang::TType& type)
229{
230 if (type.getQualifier().isPipeInput())
231 return spv::StorageClassInput;
232 else if (type.getQualifier().isPipeOutput())
233 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700234 else if (type.getBasicType() == glslang::EbtSampler)
235 return spv::StorageClassUniformConstant;
236 else if (type.getBasicType() == glslang::EbtAtomicUint)
237 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700239 if (type.getQualifier().layoutPushConstant)
240 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 if (type.getBasicType() == glslang::EbtBlock)
242 return spv::StorageClassUniform;
243 else
244 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600245 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600246 } else {
247 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700248 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
249 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600250 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
251 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400252 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600254 return spv::StorageClassFunction;
255 }
256 }
257}
258
259// Translate glslang sampler type to SPIR-V dimensionality.
260spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
261{
262 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::Esd1D: return spv::Dim1D;
264 case glslang::Esd2D: return spv::Dim2D;
265 case glslang::Esd3D: return spv::Dim3D;
266 case glslang::EsdCube: return spv::DimCube;
267 case glslang::EsdRect: return spv::DimRect;
268 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700269 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700271 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600272 return spv::Dim2D;
273 }
274}
275
276// Translate glslang type to SPIR-V precision decorations.
277spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
278{
279 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700280 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600281 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 default:
283 return spv::NoPrecision;
284 }
285}
286
287// Translate glslang type to SPIR-V block decorations.
288spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
289{
290 if (type.getBasicType() == glslang::EbtBlock) {
291 switch (type.getQualifier().storage) {
292 case glslang::EvqUniform: return spv::DecorationBlock;
293 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
294 case glslang::EvqVaryingIn: return spv::DecorationBlock;
295 case glslang::EvqVaryingOut: return spv::DecorationBlock;
296 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600298 break;
299 }
300 }
301
302 return (spv::Decoration)spv::BadValue;
303}
304
Rex Xu1da878f2016-02-21 20:59:01 +0800305// Translate glslang type to SPIR-V memory decorations.
306void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
307{
308 if (qualifier.coherent)
309 memory.push_back(spv::DecorationCoherent);
310 if (qualifier.volatil)
311 memory.push_back(spv::DecorationVolatile);
312 if (qualifier.restrict)
313 memory.push_back(spv::DecorationRestrict);
314 if (qualifier.readonly)
315 memory.push_back(spv::DecorationNonWritable);
316 if (qualifier.writeonly)
317 memory.push_back(spv::DecorationNonReadable);
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700321spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
323 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700324 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600325 case glslang::ElmRowMajor:
326 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700329 default:
330 // opaque layouts don't need a majorness
331 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600332 }
333 } else {
334 switch (type.getBasicType()) {
335 default:
336 return (spv::Decoration)spv::BadValue;
337 break;
338 case glslang::EbtBlock:
339 switch (type.getQualifier().storage) {
340 case glslang::EvqUniform:
341 case glslang::EvqBuffer:
342 switch (type.getQualifier().layoutPacking) {
343 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
345 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600346 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 }
348 case glslang::EvqVaryingIn:
349 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700350 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600351 return (spv::Decoration)spv::BadValue;
352 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700353 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return (spv::Decoration)spv::BadValue;
355 }
356 }
357 }
358}
359
360// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700361// Returns spv::Decoration(spv::BadValue) when no decoration
362// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800363spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600364{
Rex Xubbceed72016-05-21 09:40:44 +0800365 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700366 // Smooth decoration doesn't exist in SPIR-V 1.0
367 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800368 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700369 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700370 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600371 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800372 else
373 return (spv::Decoration)spv::BadValue;
374}
375
376// Translate glslang type to SPIR-V auxiliary storage decorations.
377// Returns spv::Decoration(spv::BadValue) when no decoration
378// should be applied.
379spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
380{
381 if (qualifier.patch)
382 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700383 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600384 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700385 else if (qualifier.sample) {
386 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700388 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return (spv::Decoration)spv::BadValue;
390}
391
John Kessenich92187592016-02-01 13:45:25 -0700392// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700393spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600394{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationInvariant;
397 else
398 return (spv::Decoration)spv::BadValue;
399}
400
qining9220dbb2016-05-04 17:34:38 -0400401// If glslang type is noContraction, return SPIR-V NoContraction decoration.
402spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
403{
404 if (qualifier.noContraction)
405 return spv::DecorationNoContraction;
406 else
407 return (spv::Decoration)spv::BadValue;
408}
409
David Netoa901ffe2016-06-08 14:11:40 +0100410// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
411// associated capabilities when required. For some built-in variables, a capability
412// is generated only when using the variable in an executable instruction, but not when
413// just declaring a struct member variable with it. This is true for PointSize,
414// ClipDistance, and CullDistance.
415spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600416{
417 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700418 case glslang::EbvPointSize:
David Netoa901ffe2016-06-08 14:11:40 +0100419 // Defer adding the capability until the built-in is actually used.
420 if (!memberDeclaration) {
421 switch (glslangIntermediate->getStage()) {
422 case EShLangGeometry:
423 builder.addCapability(spv::CapabilityGeometryPointSize);
424 break;
425 case EShLangTessControl:
426 case EShLangTessEvaluation:
427 builder.addCapability(spv::CapabilityTessellationPointSize);
428 break;
429 default:
430 break;
431 }
John Kessenich92187592016-02-01 13:45:25 -0700432 }
433 return spv::BuiltInPointSize;
434
John Kessenichebb50532016-05-16 19:22:05 -0600435 // These *Distance capabilities logically belong here, but if the member is declared and
436 // then never used, consumers of SPIR-V prefer the capability not be declared.
437 // They are now generated when used, rather than here when declared.
438 // Potentially, the specification should be more clear what the minimum
439 // use needed is to trigger the capability.
440 //
John Kessenich92187592016-02-01 13:45:25 -0700441 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100442 if (!memberDeclaration)
443 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700444 return spv::BuiltInClipDistance;
445
446 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100447 if (!memberDeclaration)
448 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700449 return spv::BuiltInCullDistance;
450
451 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500452 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInViewportIndex;
454
John Kessenich5e801132016-02-15 11:09:46 -0700455 case glslang::EbvSampleId:
456 builder.addCapability(spv::CapabilitySampleRateShading);
457 return spv::BuiltInSampleId;
458
459 case glslang::EbvSamplePosition:
460 builder.addCapability(spv::CapabilitySampleRateShading);
461 return spv::BuiltInSamplePosition;
462
463 case glslang::EbvSampleMask:
464 builder.addCapability(spv::CapabilitySampleRateShading);
465 return spv::BuiltInSampleMask;
466
John Kessenich140f3df2015-06-26 16:58:36 -0600467 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600468 case glslang::EbvVertexId: return spv::BuiltInVertexId;
469 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700470 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
471 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600472 case glslang::EbvBaseVertex:
473 case glslang::EbvBaseInstance:
474 case glslang::EbvDrawId:
475 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600476 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600477 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600478 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
479 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
480 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600481 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
482 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
483 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
484 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
485 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
486 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
487 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600488 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
489 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
490 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
491 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
492 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
493 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
494 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
495 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800496 case glslang::EbvSubGroupSize:
497 case glslang::EbvSubGroupInvocation:
498 case glslang::EbvSubGroupEqMask:
499 case glslang::EbvSubGroupGeMask:
500 case glslang::EbvSubGroupGtMask:
501 case glslang::EbvSubGroupLeMask:
502 case glslang::EbvSubGroupLtMask:
503 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600504 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800505 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600506 default: return (spv::BuiltIn)spv::BadValue;
507 }
508}
509
Rex Xufc618912015-09-09 16:42:49 +0800510// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700511spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800512{
513 assert(type.getBasicType() == glslang::EbtSampler);
514
John Kessenich5d0fa972016-02-15 11:57:00 -0700515 // Check for capabilities
516 switch (type.getQualifier().layoutFormat) {
517 case glslang::ElfRg32f:
518 case glslang::ElfRg16f:
519 case glslang::ElfR11fG11fB10f:
520 case glslang::ElfR16f:
521 case glslang::ElfRgba16:
522 case glslang::ElfRgb10A2:
523 case glslang::ElfRg16:
524 case glslang::ElfRg8:
525 case glslang::ElfR16:
526 case glslang::ElfR8:
527 case glslang::ElfRgba16Snorm:
528 case glslang::ElfRg16Snorm:
529 case glslang::ElfRg8Snorm:
530 case glslang::ElfR16Snorm:
531 case glslang::ElfR8Snorm:
532
533 case glslang::ElfRg32i:
534 case glslang::ElfRg16i:
535 case glslang::ElfRg8i:
536 case glslang::ElfR16i:
537 case glslang::ElfR8i:
538
539 case glslang::ElfRgb10a2ui:
540 case glslang::ElfRg32ui:
541 case glslang::ElfRg16ui:
542 case glslang::ElfRg8ui:
543 case glslang::ElfR16ui:
544 case glslang::ElfR8ui:
545 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
546 break;
547
548 default:
549 break;
550 }
551
552 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800553 switch (type.getQualifier().layoutFormat) {
554 case glslang::ElfNone: return spv::ImageFormatUnknown;
555 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
556 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
557 case glslang::ElfR32f: return spv::ImageFormatR32f;
558 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
559 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
560 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
561 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
562 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
563 case glslang::ElfR16f: return spv::ImageFormatR16f;
564 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
565 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
566 case glslang::ElfRg16: return spv::ImageFormatRg16;
567 case glslang::ElfRg8: return spv::ImageFormatRg8;
568 case glslang::ElfR16: return spv::ImageFormatR16;
569 case glslang::ElfR8: return spv::ImageFormatR8;
570 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
571 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
572 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
573 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
574 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
575 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
576 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
577 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
578 case glslang::ElfR32i: return spv::ImageFormatR32i;
579 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
580 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
581 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
582 case glslang::ElfR16i: return spv::ImageFormatR16i;
583 case glslang::ElfR8i: return spv::ImageFormatR8i;
584 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
585 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
586 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
587 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
588 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
589 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
590 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
591 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
592 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
593 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
594 default: return (spv::ImageFormat)spv::BadValue;
595 }
596}
597
qining25262b32016-05-06 17:25:16 -0400598// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700599// descriptor set.
600bool IsDescriptorResource(const glslang::TType& type)
601{
John Kessenichf7497e22016-03-08 21:36:22 -0700602 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700603 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700604 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700605
606 // non block...
607 // basically samplerXXX/subpass/sampler/texture are all included
608 // if they are the global-scope-class, not the function parameter
609 // (or local, if they ever exist) class.
610 if (type.getBasicType() == glslang::EbtSampler)
611 return type.getQualifier().isUniformOrBuffer();
612
613 // None of the above.
614 return false;
615}
616
John Kesseniche0b6cad2015-12-24 10:30:13 -0700617void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
618{
619 if (child.layoutMatrix == glslang::ElmNone)
620 child.layoutMatrix = parent.layoutMatrix;
621
622 if (parent.invariant)
623 child.invariant = true;
624 if (parent.nopersp)
625 child.nopersp = true;
626 if (parent.flat)
627 child.flat = true;
628 if (parent.centroid)
629 child.centroid = true;
630 if (parent.patch)
631 child.patch = true;
632 if (parent.sample)
633 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800634 if (parent.coherent)
635 child.coherent = true;
636 if (parent.volatil)
637 child.volatil = true;
638 if (parent.restrict)
639 child.restrict = true;
640 if (parent.readonly)
641 child.readonly = true;
642 if (parent.writeonly)
643 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700644}
645
646bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
647{
John Kessenich7b9fa252016-01-21 18:56:57 -0700648 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700649 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600650 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700651 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600652 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700653}
654
John Kessenich140f3df2015-06-26 16:58:36 -0600655//
656// Implement the TGlslangToSpvTraverser class.
657//
658
Lei Zhang17535f72016-05-04 15:55:59 -0400659TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
660 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
661 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600662 inMain(false), mainTerminated(false), linkageOnly(false),
663 glslangIntermediate(glslangIntermediate)
664{
665 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
666
667 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700668 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600669 stdBuiltins = builder.import("GLSL.std.450");
670 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700671 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
672 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600673
674 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600675 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
676 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600677 builder.addSourceExtension(it->c_str());
678
679 // Add the top-level modes for this shader.
680
John Kessenich92187592016-02-01 13:45:25 -0700681 if (glslangIntermediate->getXfbMode()) {
682 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600683 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700684 }
John Kessenich140f3df2015-06-26 16:58:36 -0600685
686 unsigned int mode;
687 switch (glslangIntermediate->getStage()) {
688 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600689 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600690 break;
691
692 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600693 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600694 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
695 break;
696
697 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600698 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600699 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700700 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
701 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
702 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600703 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600704 }
705 if (mode != spv::BadValue)
706 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
707
John Kesseniche6903322015-10-13 16:29:02 -0600708 switch (glslangIntermediate->getVertexSpacing()) {
709 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
710 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
711 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
712 default: mode = spv::BadValue; break;
713 }
714 if (mode != spv::BadValue)
715 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
716
717 switch (glslangIntermediate->getVertexOrder()) {
718 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
719 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
720 default: mode = spv::BadValue; break;
721 }
722 if (mode != spv::BadValue)
723 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
724
725 if (glslangIntermediate->getPointMode())
726 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 break;
728
729 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600730 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600731 switch (glslangIntermediate->getInputPrimitive()) {
732 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
733 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
734 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700735 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600736 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
737 default: mode = spv::BadValue; break;
738 }
739 if (mode != spv::BadValue)
740 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600741
John Kessenich140f3df2015-06-26 16:58:36 -0600742 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
743
744 switch (glslangIntermediate->getOutputPrimitive()) {
745 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
746 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
747 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
748 default: mode = spv::BadValue; break;
749 }
750 if (mode != spv::BadValue)
751 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
752 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
753 break;
754
755 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600756 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600757 if (glslangIntermediate->getPixelCenterInteger())
758 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600759
John Kessenich140f3df2015-06-26 16:58:36 -0600760 if (glslangIntermediate->getOriginUpperLeft())
761 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600762 else
763 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600764
765 if (glslangIntermediate->getEarlyFragmentTests())
766 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
767
768 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600769 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
770 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
771 default: mode = spv::BadValue; break;
772 }
773 if (mode != spv::BadValue)
774 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
775
776 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
777 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600778 break;
779
780 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600781 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600782 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
783 glslangIntermediate->getLocalSize(1),
784 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600785 break;
786
787 default:
788 break;
789 }
790
791}
792
John Kessenich7ba63412015-12-20 17:37:07 -0700793// Finish everything and dump
794void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
795{
796 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100797 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
798 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700799
qiningda397332016-03-09 19:54:03 -0500800 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700801 builder.dump(out);
802}
803
John Kessenich140f3df2015-06-26 16:58:36 -0600804TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
805{
806 if (! mainTerminated) {
807 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
808 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600809 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600810 }
811}
812
813//
814// Implement the traversal functions.
815//
816// Return true from interior nodes to have the external traversal
817// continue on to children. Return false if children were
818// already processed.
819//
820
821//
qining25262b32016-05-06 17:25:16 -0400822// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600823// - uniform/input reads
824// - output writes
825// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
826// - something simple that degenerates into the last bullet
827//
828void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
829{
qining75d1d802016-04-06 14:42:01 -0400830 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
831 if (symbol->getType().getQualifier().isSpecConstant())
832 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834 // getSymbolId() will set up all the IO decorations on the first call.
835 // Formal function parameters were mapped during makeFunctions().
836 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700837
838 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
839 if (builder.isPointer(id)) {
840 spv::StorageClass sc = builder.getStorageClass(id);
841 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
842 iOSet.insert(id);
843 }
844
845 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700846 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600847 // Prepare to generate code for the access
848
849 // L-value chains will be computed left to right. We're on the symbol now,
850 // which is the left-most part of the access chain, so now is "clear" time,
851 // followed by setting the base.
852 builder.clearAccessChain();
853
854 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700855 // except for
856 // A) "const in" arguments to a function, which are an intermediate object.
857 // See comments in handleUserFunctionCall().
858 // B) Specialization constants (normal constant don't even come in as a variable),
859 // These are also pure R-values.
860 glslang::TQualifier qualifier = symbol->getQualifier();
861 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
862 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600863 builder.setAccessChainRValue(id);
864 else
865 builder.setAccessChainLValue(id);
866 }
867}
868
869bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
870{
qining40887662016-04-03 22:20:42 -0400871 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
872 if (node->getType().getQualifier().isSpecConstant())
873 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
874
John Kessenich140f3df2015-06-26 16:58:36 -0600875 // First, handle special cases
876 switch (node->getOp()) {
877 case glslang::EOpAssign:
878 case glslang::EOpAddAssign:
879 case glslang::EOpSubAssign:
880 case glslang::EOpMulAssign:
881 case glslang::EOpVectorTimesMatrixAssign:
882 case glslang::EOpVectorTimesScalarAssign:
883 case glslang::EOpMatrixTimesScalarAssign:
884 case glslang::EOpMatrixTimesMatrixAssign:
885 case glslang::EOpDivAssign:
886 case glslang::EOpModAssign:
887 case glslang::EOpAndAssign:
888 case glslang::EOpInclusiveOrAssign:
889 case glslang::EOpExclusiveOrAssign:
890 case glslang::EOpLeftShiftAssign:
891 case glslang::EOpRightShiftAssign:
892 // A bin-op assign "a += b" means the same thing as "a = a + b"
893 // where a is evaluated before b. For a simple assignment, GLSL
894 // says to evaluate the left before the right. So, always, left
895 // node then right node.
896 {
897 // get the left l-value, save it away
898 builder.clearAccessChain();
899 node->getLeft()->traverse(this);
900 spv::Builder::AccessChain lValue = builder.getAccessChain();
901
902 // evaluate the right
903 builder.clearAccessChain();
904 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700905 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600906
907 if (node->getOp() != glslang::EOpAssign) {
908 // the left is also an r-value
909 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700910 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600911
912 // do the operation
qining25262b32016-05-06 17:25:16 -0400913 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
914 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600915 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
916 node->getType().getBasicType());
917
918 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700919 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600920 }
921
922 // store the result
923 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800924 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600925
926 // assignments are expressions having an rValue after they are evaluated...
927 builder.clearAccessChain();
928 builder.setAccessChainRValue(rValue);
929 }
930 return false;
931 case glslang::EOpIndexDirect:
932 case glslang::EOpIndexDirectStruct:
933 {
934 // Get the left part of the access chain.
935 node->getLeft()->traverse(this);
936
937 // Add the next element in the chain
938
David Netoa901ffe2016-06-08 14:11:40 +0100939 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600940 if (! node->getLeft()->getType().isArray() &&
941 node->getLeft()->getType().isVector() &&
942 node->getOp() == glslang::EOpIndexDirect) {
943 // This is essentially a hard-coded vector swizzle of size 1,
944 // so short circuit the access-chain stuff with a swizzle.
945 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100946 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600947 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600948 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100949 int spvIndex = glslangIndex;
950 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
951 node->getOp() == glslang::EOpIndexDirectStruct)
952 {
953 // This may be, e.g., an anonymous block-member selection, which generally need
954 // index remapping due to hidden members in anonymous blocks.
955 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
956 assert(remapper.size() > 0);
957 spvIndex = remapper[glslangIndex];
958 }
John Kessenichebb50532016-05-16 19:22:05 -0600959
David Netoa901ffe2016-06-08 14:11:40 +0100960 // normal case for indexing array or structure or block
961 builder.accessChainPush(builder.makeIntConstant(spvIndex));
962
963 // Add capabilities here for accessing PointSize and clip/cull distance.
964 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600965 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100966 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600967 }
968 }
969 return false;
970 case glslang::EOpIndexIndirect:
971 {
972 // Structure or array or vector indirection.
973 // Will use native SPIR-V access-chain for struct and array indirection;
974 // matrices are arrays of vectors, so will also work for a matrix.
975 // Will use the access chain's 'component' for variable index into a vector.
976
977 // This adapter is building access chains left to right.
978 // Set up the access chain to the left.
979 node->getLeft()->traverse(this);
980
981 // save it so that computing the right side doesn't trash it
982 spv::Builder::AccessChain partial = builder.getAccessChain();
983
984 // compute the next index in the chain
985 builder.clearAccessChain();
986 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700987 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600988
989 // restore the saved access chain
990 builder.setAccessChain(partial);
991
992 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600993 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600994 else
John Kessenichfa668da2015-09-13 14:46:30 -0600995 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600996 }
997 return false;
998 case glslang::EOpVectorSwizzle:
999 {
1000 node->getLeft()->traverse(this);
1001 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
1002 std::vector<unsigned> swizzle;
1003 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1004 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -06001005 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001006 }
1007 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001008 case glslang::EOpLogicalOr:
1009 case glslang::EOpLogicalAnd:
1010 {
1011
1012 // These may require short circuiting, but can sometimes be done as straight
1013 // binary operations. The right operand must be short circuited if it has
1014 // side effects, and should probably be if it is complex.
1015 if (isTrivial(node->getRight()->getAsTyped()))
1016 break; // handle below as a normal binary operation
1017 // otherwise, we need to do dynamic short circuiting on the right operand
1018 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1019 builder.clearAccessChain();
1020 builder.setAccessChainRValue(result);
1021 }
1022 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001023 default:
1024 break;
1025 }
1026
1027 // Assume generic binary op...
1028
John Kessenich32cfd492016-02-02 12:37:46 -07001029 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001030 builder.clearAccessChain();
1031 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001032 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001033
John Kessenich32cfd492016-02-02 12:37:46 -07001034 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001035 builder.clearAccessChain();
1036 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001037 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001038
John Kessenich32cfd492016-02-02 12:37:46 -07001039 // get result
1040 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001041 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001042 convertGlslangToSpvType(node->getType()), left, right,
1043 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001044
John Kessenich50e57562015-12-21 21:21:11 -07001045 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001046 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001047 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001048 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001049 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001050 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001051 return false;
1052 }
John Kessenich140f3df2015-06-26 16:58:36 -06001053}
1054
1055bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1056{
qining40887662016-04-03 22:20:42 -04001057 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1058 if (node->getType().getQualifier().isSpecConstant())
1059 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1060
John Kessenichfc51d282015-08-19 13:34:18 -06001061 spv::Id result = spv::NoResult;
1062
1063 // try texturing first
1064 result = createImageTextureFunctionCall(node);
1065 if (result != spv::NoResult) {
1066 builder.clearAccessChain();
1067 builder.setAccessChainRValue(result);
1068
1069 return false; // done with this node
1070 }
1071
1072 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001073
1074 if (node->getOp() == glslang::EOpArrayLength) {
1075 // Quite special; won't want to evaluate the operand.
1076
1077 // Normal .length() would have been constant folded by the front-end.
1078 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001079 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001080 assert(node->getOperand()->getType().isRuntimeSizedArray());
1081 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1082 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001083 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1084 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001085
1086 builder.clearAccessChain();
1087 builder.setAccessChainRValue(length);
1088
1089 return false;
1090 }
1091
John Kessenichfc51d282015-08-19 13:34:18 -06001092 // Start by evaluating the operand
1093
John Kessenich140f3df2015-06-26 16:58:36 -06001094 builder.clearAccessChain();
1095 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001096
Rex Xufc618912015-09-09 16:42:49 +08001097 spv::Id operand = spv::NoResult;
1098
1099 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1100 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001101 node->getOp() == glslang::EOpAtomicCounter ||
1102 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001103 operand = builder.accessChainGetLValue(); // Special case l-value operands
1104 else
John Kessenich32cfd492016-02-02 12:37:46 -07001105 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001106
1107 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001108 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001111 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001112 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001113
1114 // if not, then possibly an operation
1115 if (! result)
qining25262b32016-05-06 17:25:16 -04001116 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001117
1118 if (result) {
1119 builder.clearAccessChain();
1120 builder.setAccessChainRValue(result);
1121
1122 return false; // done with this node
1123 }
1124
1125 // it must be a special case, check...
1126 switch (node->getOp()) {
1127 case glslang::EOpPostIncrement:
1128 case glslang::EOpPostDecrement:
1129 case glslang::EOpPreIncrement:
1130 case glslang::EOpPreDecrement:
1131 {
1132 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001133 spv::Id one = 0;
1134 if (node->getBasicType() == glslang::EbtFloat)
1135 one = builder.makeFloatConstant(1.0F);
1136 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1137 one = builder.makeInt64Constant(1);
1138 else
1139 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001140 glslang::TOperator op;
1141 if (node->getOp() == glslang::EOpPreIncrement ||
1142 node->getOp() == glslang::EOpPostIncrement)
1143 op = glslang::EOpAdd;
1144 else
1145 op = glslang::EOpSub;
1146
qining25262b32016-05-06 17:25:16 -04001147 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1148 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001149 convertGlslangToSpvType(node->getType()), operand, one,
1150 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001151 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001152
1153 // The result of operation is always stored, but conditionally the
1154 // consumed result. The consumed result is always an r-value.
1155 builder.accessChainStore(result);
1156 builder.clearAccessChain();
1157 if (node->getOp() == glslang::EOpPreIncrement ||
1158 node->getOp() == glslang::EOpPreDecrement)
1159 builder.setAccessChainRValue(result);
1160 else
1161 builder.setAccessChainRValue(operand);
1162 }
1163
1164 return false;
1165
1166 case glslang::EOpEmitStreamVertex:
1167 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1168 return false;
1169 case glslang::EOpEndStreamPrimitive:
1170 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1171 return false;
1172
1173 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001174 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001175 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001176 }
John Kessenich140f3df2015-06-26 16:58:36 -06001177}
1178
1179bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1180{
qining27e04a02016-04-14 16:40:20 -04001181 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1182 if (node->getType().getQualifier().isSpecConstant())
1183 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1184
John Kessenichfc51d282015-08-19 13:34:18 -06001185 spv::Id result = spv::NoResult;
1186
1187 // try texturing
1188 result = createImageTextureFunctionCall(node);
1189 if (result != spv::NoResult) {
1190 builder.clearAccessChain();
1191 builder.setAccessChainRValue(result);
1192
1193 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001194 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001195 // "imageStore" is a special case, which has no result
1196 return false;
1197 }
John Kessenichfc51d282015-08-19 13:34:18 -06001198
John Kessenich140f3df2015-06-26 16:58:36 -06001199 glslang::TOperator binOp = glslang::EOpNull;
1200 bool reduceComparison = true;
1201 bool isMatrix = false;
1202 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001203 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001204
1205 assert(node->getOp());
1206
1207 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1208
1209 switch (node->getOp()) {
1210 case glslang::EOpSequence:
1211 {
1212 if (preVisit)
1213 ++sequenceDepth;
1214 else
1215 --sequenceDepth;
1216
1217 if (sequenceDepth == 1) {
1218 // If this is the parent node of all the functions, we want to see them
1219 // early, so all call points have actual SPIR-V functions to reference.
1220 // In all cases, still let the traverser visit the children for us.
1221 makeFunctions(node->getAsAggregate()->getSequence());
1222
1223 // Also, we want all globals initializers to go into the entry of main(), before
1224 // anything else gets there, so visit out of order, doing them all now.
1225 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1226
1227 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1228 // so do them manually.
1229 visitFunctions(node->getAsAggregate()->getSequence());
1230
1231 return false;
1232 }
1233
1234 return true;
1235 }
1236 case glslang::EOpLinkerObjects:
1237 {
1238 if (visit == glslang::EvPreVisit)
1239 linkageOnly = true;
1240 else
1241 linkageOnly = false;
1242
1243 return true;
1244 }
1245 case glslang::EOpComma:
1246 {
1247 // processing from left to right naturally leaves the right-most
1248 // lying around in the access chain
1249 glslang::TIntermSequence& glslangOperands = node->getSequence();
1250 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1251 glslangOperands[i]->traverse(this);
1252
1253 return false;
1254 }
1255 case glslang::EOpFunction:
1256 if (visit == glslang::EvPreVisit) {
1257 if (isShaderEntrypoint(node)) {
1258 inMain = true;
1259 builder.setBuildPoint(shaderEntry->getLastBlock());
1260 } else {
1261 handleFunctionEntry(node);
1262 }
1263 } else {
1264 if (inMain)
1265 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001266 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001267 inMain = false;
1268 }
1269
1270 return true;
1271 case glslang::EOpParameters:
1272 // Parameters will have been consumed by EOpFunction processing, but not
1273 // the body, so we still visited the function node's children, making this
1274 // child redundant.
1275 return false;
1276 case glslang::EOpFunctionCall:
1277 {
1278 if (node->isUserDefined())
1279 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001280 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1281 if (result) {
1282 builder.clearAccessChain();
1283 builder.setAccessChainRValue(result);
1284 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001285 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001286
1287 return false;
1288 }
1289 case glslang::EOpConstructMat2x2:
1290 case glslang::EOpConstructMat2x3:
1291 case glslang::EOpConstructMat2x4:
1292 case glslang::EOpConstructMat3x2:
1293 case glslang::EOpConstructMat3x3:
1294 case glslang::EOpConstructMat3x4:
1295 case glslang::EOpConstructMat4x2:
1296 case glslang::EOpConstructMat4x3:
1297 case glslang::EOpConstructMat4x4:
1298 case glslang::EOpConstructDMat2x2:
1299 case glslang::EOpConstructDMat2x3:
1300 case glslang::EOpConstructDMat2x4:
1301 case glslang::EOpConstructDMat3x2:
1302 case glslang::EOpConstructDMat3x3:
1303 case glslang::EOpConstructDMat3x4:
1304 case glslang::EOpConstructDMat4x2:
1305 case glslang::EOpConstructDMat4x3:
1306 case glslang::EOpConstructDMat4x4:
1307 isMatrix = true;
1308 // fall through
1309 case glslang::EOpConstructFloat:
1310 case glslang::EOpConstructVec2:
1311 case glslang::EOpConstructVec3:
1312 case glslang::EOpConstructVec4:
1313 case glslang::EOpConstructDouble:
1314 case glslang::EOpConstructDVec2:
1315 case glslang::EOpConstructDVec3:
1316 case glslang::EOpConstructDVec4:
1317 case glslang::EOpConstructBool:
1318 case glslang::EOpConstructBVec2:
1319 case glslang::EOpConstructBVec3:
1320 case glslang::EOpConstructBVec4:
1321 case glslang::EOpConstructInt:
1322 case glslang::EOpConstructIVec2:
1323 case glslang::EOpConstructIVec3:
1324 case glslang::EOpConstructIVec4:
1325 case glslang::EOpConstructUint:
1326 case glslang::EOpConstructUVec2:
1327 case glslang::EOpConstructUVec3:
1328 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001329 case glslang::EOpConstructInt64:
1330 case glslang::EOpConstructI64Vec2:
1331 case glslang::EOpConstructI64Vec3:
1332 case glslang::EOpConstructI64Vec4:
1333 case glslang::EOpConstructUint64:
1334 case glslang::EOpConstructU64Vec2:
1335 case glslang::EOpConstructU64Vec3:
1336 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001337 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001338 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001339 {
1340 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001341 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001342 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1343 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001344 if (node->getOp() == glslang::EOpConstructTextureSampler)
1345 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1346 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001347 std::vector<spv::Id> constituents;
1348 for (int c = 0; c < (int)arguments.size(); ++c)
1349 constituents.push_back(arguments[c]);
1350 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001351 } else if (isMatrix)
1352 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1353 else
1354 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 builder.clearAccessChain();
1357 builder.setAccessChainRValue(constructed);
1358
1359 return false;
1360 }
1361
1362 // These six are component-wise compares with component-wise results.
1363 // Forward on to createBinaryOperation(), requesting a vector result.
1364 case glslang::EOpLessThan:
1365 case glslang::EOpGreaterThan:
1366 case glslang::EOpLessThanEqual:
1367 case glslang::EOpGreaterThanEqual:
1368 case glslang::EOpVectorEqual:
1369 case glslang::EOpVectorNotEqual:
1370 {
1371 // Map the operation to a binary
1372 binOp = node->getOp();
1373 reduceComparison = false;
1374 switch (node->getOp()) {
1375 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1376 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1377 default: binOp = node->getOp(); break;
1378 }
1379
1380 break;
1381 }
1382 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001383 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001384 binOp = glslang::EOpMul;
1385 break;
1386 case glslang::EOpOuterProduct:
1387 // two vectors multiplied to make a matrix
1388 binOp = glslang::EOpOuterProduct;
1389 break;
1390 case glslang::EOpDot:
1391 {
qining25262b32016-05-06 17:25:16 -04001392 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001393 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001394 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001395 binOp = glslang::EOpMul;
1396 break;
1397 }
1398 case glslang::EOpMod:
1399 // when an aggregate, this is the floating-point mod built-in function,
1400 // which can be emitted by the one in createBinaryOperation()
1401 binOp = glslang::EOpMod;
1402 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001403 case glslang::EOpEmitVertex:
1404 case glslang::EOpEndPrimitive:
1405 case glslang::EOpBarrier:
1406 case glslang::EOpMemoryBarrier:
1407 case glslang::EOpMemoryBarrierAtomicCounter:
1408 case glslang::EOpMemoryBarrierBuffer:
1409 case glslang::EOpMemoryBarrierImage:
1410 case glslang::EOpMemoryBarrierShared:
1411 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001412 case glslang::EOpAllMemoryBarrierWithGroupSync:
1413 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1414 case glslang::EOpWorkgroupMemoryBarrier:
1415 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001416 noReturnValue = true;
1417 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1418 break;
1419
John Kessenich426394d2015-07-23 10:22:48 -06001420 case glslang::EOpAtomicAdd:
1421 case glslang::EOpAtomicMin:
1422 case glslang::EOpAtomicMax:
1423 case glslang::EOpAtomicAnd:
1424 case glslang::EOpAtomicOr:
1425 case glslang::EOpAtomicXor:
1426 case glslang::EOpAtomicExchange:
1427 case glslang::EOpAtomicCompSwap:
1428 atomic = true;
1429 break;
1430
John Kessenich140f3df2015-06-26 16:58:36 -06001431 default:
1432 break;
1433 }
1434
1435 //
1436 // See if it maps to a regular operation.
1437 //
John Kessenich140f3df2015-06-26 16:58:36 -06001438 if (binOp != glslang::EOpNull) {
1439 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1440 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1441 assert(left && right);
1442
1443 builder.clearAccessChain();
1444 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001445 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001446
1447 builder.clearAccessChain();
1448 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001449 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001450
qining25262b32016-05-06 17:25:16 -04001451 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1452 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001453 left->getType().getBasicType(), reduceComparison);
1454
1455 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001456 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001457 builder.clearAccessChain();
1458 builder.setAccessChainRValue(result);
1459
1460 return false;
1461 }
1462
John Kessenich426394d2015-07-23 10:22:48 -06001463 //
1464 // Create the list of operands.
1465 //
John Kessenich140f3df2015-06-26 16:58:36 -06001466 glslang::TIntermSequence& glslangOperands = node->getSequence();
1467 std::vector<spv::Id> operands;
1468 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1469 builder.clearAccessChain();
1470 glslangOperands[arg]->traverse(this);
1471
1472 // special case l-value operands; there are just a few
1473 bool lvalue = false;
1474 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001475 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001476 case glslang::EOpModf:
1477 if (arg == 1)
1478 lvalue = true;
1479 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001480 case glslang::EOpInterpolateAtSample:
1481 case glslang::EOpInterpolateAtOffset:
1482 if (arg == 0)
1483 lvalue = true;
1484 break;
Rex Xud4782c12015-09-06 16:30:11 +08001485 case glslang::EOpAtomicAdd:
1486 case glslang::EOpAtomicMin:
1487 case glslang::EOpAtomicMax:
1488 case glslang::EOpAtomicAnd:
1489 case glslang::EOpAtomicOr:
1490 case glslang::EOpAtomicXor:
1491 case glslang::EOpAtomicExchange:
1492 case glslang::EOpAtomicCompSwap:
1493 if (arg == 0)
1494 lvalue = true;
1495 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001496 case glslang::EOpAddCarry:
1497 case glslang::EOpSubBorrow:
1498 if (arg == 2)
1499 lvalue = true;
1500 break;
1501 case glslang::EOpUMulExtended:
1502 case glslang::EOpIMulExtended:
1503 if (arg >= 2)
1504 lvalue = true;
1505 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001506 default:
1507 break;
1508 }
1509 if (lvalue)
1510 operands.push_back(builder.accessChainGetLValue());
1511 else
John Kessenich32cfd492016-02-02 12:37:46 -07001512 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001513 }
John Kessenich426394d2015-07-23 10:22:48 -06001514
1515 if (atomic) {
1516 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001517 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001518 } else {
1519 // Pass through to generic operations.
1520 switch (glslangOperands.size()) {
1521 case 0:
1522 result = createNoArgOperation(node->getOp());
1523 break;
1524 case 1:
qining25262b32016-05-06 17:25:16 -04001525 result = createUnaryOperation(
1526 node->getOp(), precision,
1527 TranslateNoContractionDecoration(node->getType().getQualifier()),
1528 convertGlslangToSpvType(node->getType()), operands.front(),
1529 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001530 break;
1531 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001532 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001533 break;
1534 }
John Kessenich140f3df2015-06-26 16:58:36 -06001535 }
1536
1537 if (noReturnValue)
1538 return false;
1539
1540 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001541 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001542 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001543 } else {
1544 builder.clearAccessChain();
1545 builder.setAccessChainRValue(result);
1546 return false;
1547 }
1548}
1549
1550bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1551{
1552 // This path handles both if-then-else and ?:
1553 // The if-then-else has a node type of void, while
1554 // ?: has a non-void node type
1555 spv::Id result = 0;
1556 if (node->getBasicType() != glslang::EbtVoid) {
1557 // don't handle this as just on-the-fly temporaries, because there will be two names
1558 // and better to leave SSA to later passes
1559 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1560 }
1561
1562 // emit the condition before doing anything with selection
1563 node->getCondition()->traverse(this);
1564
1565 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001566 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001567
1568 if (node->getTrueBlock()) {
1569 // emit the "then" statement
1570 node->getTrueBlock()->traverse(this);
1571 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001572 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001573 }
1574
1575 if (node->getFalseBlock()) {
1576 ifBuilder.makeBeginElse();
1577 // emit the "else" statement
1578 node->getFalseBlock()->traverse(this);
1579 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001580 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001581 }
1582
1583 ifBuilder.makeEndIf();
1584
1585 if (result) {
1586 // GLSL only has r-values as the result of a :?, but
1587 // if we have an l-value, that can be more efficient if it will
1588 // become the base of a complex r-value expression, because the
1589 // next layer copies r-values into memory to use the access-chain mechanism
1590 builder.clearAccessChain();
1591 builder.setAccessChainLValue(result);
1592 }
1593
1594 return false;
1595}
1596
1597bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1598{
1599 // emit and get the condition before doing anything with switch
1600 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001601 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001602
1603 // browse the children to sort out code segments
1604 int defaultSegment = -1;
1605 std::vector<TIntermNode*> codeSegments;
1606 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1607 std::vector<int> caseValues;
1608 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1609 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1610 TIntermNode* child = *c;
1611 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001612 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001613 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001614 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001615 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1616 } else
1617 codeSegments.push_back(child);
1618 }
1619
qining25262b32016-05-06 17:25:16 -04001620 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001621 // statements between the last case and the end of the switch statement
1622 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1623 (int)codeSegments.size() == defaultSegment)
1624 codeSegments.push_back(nullptr);
1625
1626 // make the switch statement
1627 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001628 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001629
1630 // emit all the code in the segments
1631 breakForLoop.push(false);
1632 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1633 builder.nextSwitchSegment(segmentBlocks, s);
1634 if (codeSegments[s])
1635 codeSegments[s]->traverse(this);
1636 else
1637 builder.addSwitchBreak();
1638 }
1639 breakForLoop.pop();
1640
1641 builder.endSwitch(segmentBlocks);
1642
1643 return false;
1644}
1645
1646void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1647{
1648 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001649 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001650
1651 builder.clearAccessChain();
1652 builder.setAccessChainRValue(constant);
1653}
1654
1655bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1656{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001657 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001658 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001659 // Spec requires back edges to target header blocks, and every header block
1660 // must dominate its merge block. Make a header block first to ensure these
1661 // conditions are met. By definition, it will contain OpLoopMerge, followed
1662 // by a block-ending branch. But we don't want to put any other body/test
1663 // instructions in it, since the body/test may have arbitrary instructions,
1664 // including merges of its own.
1665 builder.setBuildPoint(&blocks.head);
1666 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001667 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001668 spv::Block& test = builder.makeNewBlock();
1669 builder.createBranch(&test);
1670
1671 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001672 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001674 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001675 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1676
1677 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001678 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001679 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001680 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001681 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001682 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001683
1684 builder.setBuildPoint(&blocks.continue_target);
1685 if (node->getTerminal())
1686 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001687 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001688 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001689 builder.createBranch(&blocks.body);
1690
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001691 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001692 builder.setBuildPoint(&blocks.body);
1693 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001694 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001695 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001696 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001697
1698 builder.setBuildPoint(&blocks.continue_target);
1699 if (node->getTerminal())
1700 node->getTerminal()->traverse(this);
1701 if (node->getTest()) {
1702 node->getTest()->traverse(this);
1703 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001704 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001705 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001706 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001707 // TODO: unless there was a break/return/discard instruction
1708 // somewhere in the body, this is an infinite loop, so we should
1709 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001710 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001711 }
John Kessenich140f3df2015-06-26 16:58:36 -06001712 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001713 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001714 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001715 return false;
1716}
1717
1718bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1719{
1720 if (node->getExpression())
1721 node->getExpression()->traverse(this);
1722
1723 switch (node->getFlowOp()) {
1724 case glslang::EOpKill:
1725 builder.makeDiscard();
1726 break;
1727 case glslang::EOpBreak:
1728 if (breakForLoop.top())
1729 builder.createLoopExit();
1730 else
1731 builder.addSwitchBreak();
1732 break;
1733 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001734 builder.createLoopContinue();
1735 break;
1736 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001737 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001738 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001739 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001740 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001741
1742 builder.clearAccessChain();
1743 break;
1744
1745 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001746 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001747 break;
1748 }
1749
1750 return false;
1751}
1752
1753spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1754{
qining25262b32016-05-06 17:25:16 -04001755 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001756 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001757 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001758 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001759 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001760 }
1761
1762 // Now, handle actual variables
1763 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1764 spv::Id spvType = convertGlslangToSpvType(node->getType());
1765
1766 const char* name = node->getName().c_str();
1767 if (glslang::IsAnonymous(name))
1768 name = "";
1769
1770 return builder.createVariable(storageClass, spvType, name);
1771}
1772
1773// Return type Id of the sampled type.
1774spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1775{
1776 switch (sampler.type) {
1777 case glslang::EbtFloat: return builder.makeFloatType(32);
1778 case glslang::EbtInt: return builder.makeIntType(32);
1779 case glslang::EbtUint: return builder.makeUintType(32);
1780 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001781 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001782 return builder.makeFloatType(32);
1783 }
1784}
1785
John Kessenich3ac051e2015-12-20 11:29:16 -07001786// Convert from a glslang type to an SPV type, by calling into a
1787// recursive version of this function. This establishes the inherited
1788// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001789spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1790{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001791 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001792}
1793
1794// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001795// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001796// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001797spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001798{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001799 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001800
1801 switch (type.getBasicType()) {
1802 case glslang::EbtVoid:
1803 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001804 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001805 break;
1806 case glslang::EbtFloat:
1807 spvType = builder.makeFloatType(32);
1808 break;
1809 case glslang::EbtDouble:
1810 spvType = builder.makeFloatType(64);
1811 break;
1812 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001813 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1814 // a 32-bit int where non-0 means true.
1815 if (explicitLayout != glslang::ElpNone)
1816 spvType = builder.makeUintType(32);
1817 else
1818 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001819 break;
1820 case glslang::EbtInt:
1821 spvType = builder.makeIntType(32);
1822 break;
1823 case glslang::EbtUint:
1824 spvType = builder.makeUintType(32);
1825 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001826 case glslang::EbtInt64:
1827 builder.addCapability(spv::CapabilityInt64);
1828 spvType = builder.makeIntType(64);
1829 break;
1830 case glslang::EbtUint64:
1831 builder.addCapability(spv::CapabilityInt64);
1832 spvType = builder.makeUintType(64);
1833 break;
John Kessenich426394d2015-07-23 10:22:48 -06001834 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001835 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 -06001836 spvType = builder.makeUintType(32);
1837 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001838 case glslang::EbtSampler:
1839 {
1840 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001841 if (sampler.sampler) {
1842 // pure sampler
1843 spvType = builder.makeSamplerType();
1844 } else {
1845 // an image is present, make its type
1846 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1847 sampler.image ? 2 : 1, TranslateImageFormat(type));
1848 if (sampler.combined) {
1849 // already has both image and sampler, make the combined type
1850 spvType = builder.makeSampledImageType(spvType);
1851 }
John Kessenich55e7d112015-11-15 21:33:39 -07001852 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001853 }
John Kessenich140f3df2015-06-26 16:58:36 -06001854 break;
1855 case glslang::EbtStruct:
1856 case glslang::EbtBlock:
1857 {
1858 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001859 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001860
1861 // Try to share structs for different layouts, but not yet for other
1862 // kinds of qualification (primarily not yet including interpolant qualification).
1863 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001864 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001865 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001866 break;
1867
1868 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001869 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001870 memberRemapper[glslangMembers].resize(glslangMembers->size());
1871 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
1873 break;
1874 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001875 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001876 break;
1877 }
1878
1879 if (type.isMatrix())
1880 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1881 else {
1882 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1883 if (type.getVectorSize() > 1)
1884 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1885 }
1886
1887 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001888 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1889
John Kessenichc9a80832015-09-12 12:17:44 -06001890 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001891 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001892 // We need to decorate array strides for types needing explicit layout, except blocks.
1893 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001894 // Use a dummy glslang type for querying internal strides of
1895 // arrays of arrays, but using just a one-dimensional array.
1896 glslang::TType simpleArrayType(type, 0); // deference type of the array
1897 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1898 simpleArrayType.getArraySizes().dereference();
1899
1900 // Will compute the higher-order strides here, rather than making a whole
1901 // pile of types and doing repetitive recursion on their contents.
1902 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1903 }
John Kessenichf8842e52016-01-04 19:22:56 -07001904
1905 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001906 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001907 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001908 if (stride > 0)
1909 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001910 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001911 }
1912 } else {
1913 // single-dimensional array, and don't yet have stride
1914
John Kessenichf8842e52016-01-04 19:22:56 -07001915 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001916 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1917 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001918 }
John Kessenich31ed4832015-09-09 17:51:38 -06001919
John Kessenichc9a80832015-09-12 12:17:44 -06001920 // Do the outer dimension, which might not be known for a runtime-sized array
1921 if (type.isRuntimeSizedArray()) {
1922 spvType = builder.makeRuntimeArray(spvType);
1923 } else {
1924 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001925 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001926 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001927 if (stride > 0)
1928 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001929 }
1930
1931 return spvType;
1932}
1933
John Kessenich6090df02016-06-30 21:18:02 -06001934
1935// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
1936// explicitLayout can be kept the same throughout the hierarchical recursive walk.
1937// Mutually recursive with convertGlslangToSpvType().
1938spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
1939 const glslang::TTypeList* glslangMembers,
1940 glslang::TLayoutPacking explicitLayout,
1941 const glslang::TQualifier& qualifier)
1942{
1943 // Create a vector of struct types for SPIR-V to consume
1944 std::vector<spv::Id> spvMembers;
1945 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1946 int locationOffset = 0; // for use across struct members, when they are called recursively
1947 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1948 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1949 if (glslangMember.hiddenMember()) {
1950 ++memberDelta;
1951 if (type.getBasicType() == glslang::EbtBlock)
1952 memberRemapper[glslangMembers][i] = -1;
1953 } else {
1954 if (type.getBasicType() == glslang::EbtBlock)
1955 memberRemapper[glslangMembers][i] = i - memberDelta;
1956 // modify just this child's view of the qualifier
1957 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
1958 InheritQualifiers(memberQualifier, qualifier);
1959
1960 // manually inherit location; it's more complex
1961 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
1962 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1963 if (qualifier.hasLocation())
1964 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
1965
1966 // recurse
1967 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
1968 }
1969 }
1970
1971 // Make the SPIR-V type
1972 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
1973 if (! HasNonLayoutQualifiers(qualifier))
1974 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
1975
1976 // Decorate it
1977 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
1978
1979 return spvType;
1980}
1981
1982void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
1983 const glslang::TTypeList* glslangMembers,
1984 glslang::TLayoutPacking explicitLayout,
1985 const glslang::TQualifier& qualifier,
1986 spv::Id spvType)
1987{
1988 // Name and decorate the non-hidden members
1989 int offset = -1;
1990 int locationOffset = 0; // for use within the members of this struct
1991 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1992 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1993 int member = i;
1994 if (type.getBasicType() == glslang::EbtBlock)
1995 member = memberRemapper[glslangMembers][i];
1996
1997 // modify just this child's view of the qualifier
1998 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
1999 InheritQualifiers(memberQualifier, qualifier);
2000
2001 // using -1 above to indicate a hidden member
2002 if (member >= 0) {
2003 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2004 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2005 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2006 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2007 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2008 if (type.getBasicType() == glslang::EbtBlock) {
2009 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2010 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2011 }
2012 }
2013 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2014
2015 if (qualifier.storage == glslang::EvqBuffer) {
2016 std::vector<spv::Decoration> memory;
2017 TranslateMemoryDecoration(memberQualifier, memory);
2018 for (unsigned int i = 0; i < memory.size(); ++i)
2019 addMemberDecoration(spvType, member, memory[i]);
2020 }
2021
John Kessenich2f47bc92016-06-30 21:47:35 -06002022 // Compute location decoration; tricky based on whether inheritance is at play and
2023 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002024 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2025 // probably move to the linker stage of the front end proper, and just have the
2026 // answer sitting already distributed throughout the individual member locations.
2027 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002028 // Ignore member locations if the container is an array, as that's
2029 // ill-specified and decisions have been made to not allow this anyway.
2030 // The object itself must have a location, and that comes out from decorating the object,
2031 // not the type (this code decorates types).
2032 if (! type.isArray()) {
2033 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2034 // struct members should not have explicit locations
2035 assert(type.getBasicType() != glslang::EbtStruct);
2036 location = memberQualifier.layoutLocation;
2037 } else if (type.getBasicType() != glslang::EbtBlock) {
2038 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2039 // The members, and their nested types, must not themselves have Location decorations.
2040 } else if (qualifier.hasLocation()) // inheritance
2041 location = qualifier.layoutLocation + locationOffset;
2042 }
John Kessenich6090df02016-06-30 21:18:02 -06002043 if (location >= 0)
2044 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2045
John Kessenich2f47bc92016-06-30 21:47:35 -06002046 if (qualifier.hasLocation()) // track for upcoming inheritance
2047 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2048
John Kessenich6090df02016-06-30 21:18:02 -06002049 // component, XFB, others
2050 if (glslangMember.getQualifier().hasComponent())
2051 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2052 if (glslangMember.getQualifier().hasXfbOffset())
2053 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2054 else if (explicitLayout != glslang::ElpNone) {
2055 // figure out what to do with offset, which is accumulating
2056 int nextOffset;
2057 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2058 if (offset >= 0)
2059 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2060 offset = nextOffset;
2061 }
2062
2063 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2064 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2065
2066 // built-in variable decorations
2067 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2068 if (builtIn != spv::BadValue)
2069 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2070 }
2071 }
2072
2073 // Decorate the structure
2074 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2075 addDecoration(spvType, TranslateBlockDecoration(type));
2076 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2077 builder.addCapability(spv::CapabilityGeometryStreams);
2078 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2079 }
2080 if (glslangIntermediate->getXfbMode()) {
2081 builder.addCapability(spv::CapabilityTransformFeedback);
2082 if (type.getQualifier().hasXfbStride())
2083 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2084 if (type.getQualifier().hasXfbBuffer())
2085 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2086 }
2087}
2088
John Kessenich6c292d32016-02-15 20:58:50 -07002089// Turn the expression forming the array size into an id.
2090// This is not quite trivial, because of specialization constants.
2091// Sometimes, a raw constant is turned into an Id, and sometimes
2092// a specialization constant expression is.
2093spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2094{
2095 // First, see if this is sized with a node, meaning a specialization constant:
2096 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2097 if (specNode != nullptr) {
2098 builder.clearAccessChain();
2099 specNode->traverse(this);
2100 return accessChainLoad(specNode->getAsTyped()->getType());
2101 }
qining25262b32016-05-06 17:25:16 -04002102
John Kessenich6c292d32016-02-15 20:58:50 -07002103 // Otherwise, need a compile-time (front end) size, get it:
2104 int size = arraySizes.getDimSize(dim);
2105 assert(size > 0);
2106 return builder.makeUintConstant(size);
2107}
2108
John Kessenich103bef92016-02-08 21:38:15 -07002109// Wrap the builder's accessChainLoad to:
2110// - localize handling of RelaxedPrecision
2111// - use the SPIR-V inferred type instead of another conversion of the glslang type
2112// (avoids unnecessary work and possible type punning for structures)
2113// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002114spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2115{
John Kessenich103bef92016-02-08 21:38:15 -07002116 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2117 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2118
2119 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002120 if (type.getBasicType() == glslang::EbtBool) {
2121 if (builder.isScalarType(nominalTypeId)) {
2122 // Conversion for bool
2123 spv::Id boolType = builder.makeBoolType();
2124 if (nominalTypeId != boolType)
2125 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2126 } else if (builder.isVectorType(nominalTypeId)) {
2127 // Conversion for bvec
2128 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2129 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2130 if (nominalTypeId != bvecType)
2131 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2132 }
2133 }
John Kessenich103bef92016-02-08 21:38:15 -07002134
2135 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002136}
2137
Rex Xu27253232016-02-23 17:51:09 +08002138// Wrap the builder's accessChainStore to:
2139// - do conversion of concrete to abstract type
2140void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2141{
2142 // Need to convert to abstract types when necessary
2143 if (type.getBasicType() == glslang::EbtBool) {
2144 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2145
2146 if (builder.isScalarType(nominalTypeId)) {
2147 // Conversion for bool
2148 spv::Id boolType = builder.makeBoolType();
2149 if (nominalTypeId != boolType) {
2150 spv::Id zero = builder.makeUintConstant(0);
2151 spv::Id one = builder.makeUintConstant(1);
2152 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2153 }
2154 } else if (builder.isVectorType(nominalTypeId)) {
2155 // Conversion for bvec
2156 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2157 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2158 if (nominalTypeId != bvecType) {
2159 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2160 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2161 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2162 }
2163 }
2164 }
2165
2166 builder.accessChainStore(rvalue);
2167}
2168
John Kessenichf85e8062015-12-19 13:57:10 -07002169// Decide whether or not this type should be
2170// decorated with offsets and strides, and if so
2171// whether std140 or std430 rules should be applied.
2172glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002173{
John Kessenichf85e8062015-12-19 13:57:10 -07002174 // has to be a block
2175 if (type.getBasicType() != glslang::EbtBlock)
2176 return glslang::ElpNone;
2177
2178 // has to be a uniform or buffer block
2179 if (type.getQualifier().storage != glslang::EvqUniform &&
2180 type.getQualifier().storage != glslang::EvqBuffer)
2181 return glslang::ElpNone;
2182
2183 // return the layout to use
2184 switch (type.getQualifier().layoutPacking) {
2185 case glslang::ElpStd140:
2186 case glslang::ElpStd430:
2187 return type.getQualifier().layoutPacking;
2188 default:
2189 return glslang::ElpNone;
2190 }
John Kessenich31ed4832015-09-09 17:51:38 -06002191}
2192
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002193// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002194int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002195{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002196 int size;
John Kessenich49987892015-12-29 17:11:44 -07002197 int stride;
2198 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002199
2200 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002201}
2202
John Kessenich49987892015-12-29 17:11:44 -07002203// 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 -07002204// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002205int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002206{
John Kessenich49987892015-12-29 17:11:44 -07002207 glslang::TType elementType;
2208 elementType.shallowCopy(matrixType);
2209 elementType.clearArraySizes();
2210
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002211 int size;
John Kessenich49987892015-12-29 17:11:44 -07002212 int stride;
2213 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2214
2215 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002216}
2217
John Kessenich5e4b1242015-08-06 22:53:06 -06002218// Given a member type of a struct, realign the current offset for it, and compute
2219// the next (not yet aligned) offset for the next member, which will get aligned
2220// on the next call.
2221// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2222// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2223// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002224void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002225 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002226{
2227 // this will get a positive value when deemed necessary
2228 nextOffset = -1;
2229
John Kessenich5e4b1242015-08-06 22:53:06 -06002230 // override anything in currentOffset with user-set offset
2231 if (memberType.getQualifier().hasOffset())
2232 currentOffset = memberType.getQualifier().layoutOffset;
2233
2234 // It could be that current linker usage in glslang updated all the layoutOffset,
2235 // in which case the following code does not matter. But, that's not quite right
2236 // once cross-compilation unit GLSL validation is done, as the original user
2237 // settings are needed in layoutOffset, and then the following will come into play.
2238
John Kessenichf85e8062015-12-19 13:57:10 -07002239 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002240 if (! memberType.getQualifier().hasOffset())
2241 currentOffset = -1;
2242
2243 return;
2244 }
2245
John Kessenichf85e8062015-12-19 13:57:10 -07002246 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002247 if (currentOffset < 0)
2248 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002249
John Kessenich5e4b1242015-08-06 22:53:06 -06002250 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2251 // but possibly not yet correctly aligned.
2252
2253 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002254 int dummyStride;
2255 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002256 glslang::RoundToPow2(currentOffset, memberAlignment);
2257 nextOffset = currentOffset + memberSize;
2258}
2259
David Netoa901ffe2016-06-08 14:11:40 +01002260void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002261{
David Netoa901ffe2016-06-08 14:11:40 +01002262 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2263 switch (glslangBuiltIn)
2264 {
2265 case glslang::EbvClipDistance:
2266 case glslang::EbvCullDistance:
2267 case glslang::EbvPointSize:
2268 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2269 // Alternately, we could just call this for any glslang built-in, since the
2270 // capability already guards against duplicates.
2271 TranslateBuiltInDecoration(glslangBuiltIn, false);
2272 break;
2273 default:
2274 // Capabilities were already generated when the struct was declared.
2275 break;
2276 }
John Kessenichebb50532016-05-16 19:22:05 -06002277}
2278
John Kessenich140f3df2015-06-26 16:58:36 -06002279bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2280{
John Kessenich4d65ee32016-03-12 18:17:47 -07002281 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002282 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002283 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002284}
2285
2286// Make all the functions, skeletally, without actually visiting their bodies.
2287void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2288{
2289 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2290 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2291 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2292 continue;
2293
2294 // We're on a user function. Set up the basic interface for the function now,
2295 // so that it's available to call.
2296 // Translating the body will happen later.
2297 //
qining25262b32016-05-06 17:25:16 -04002298 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002299 // function. What it is an address of varies:
2300 //
2301 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2302 // so that write needs to be to a copy, hence the address of a copy works.
2303 //
2304 // - "const in" parameters can just be the r-value, as no writes need occur.
2305 //
2306 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2307 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2308
2309 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002310 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002311 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2312
2313 for (int p = 0; p < (int)parameters.size(); ++p) {
2314 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2315 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002316 if (paramType.isOpaque())
2317 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2318 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002319 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2320 else
2321 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002322 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002323 paramTypes.push_back(typeId);
2324 }
2325
2326 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002327 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2328 convertGlslangToSpvType(glslFunction->getType()),
2329 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002330
2331 // Track function to emit/call later
2332 functionMap[glslFunction->getName().c_str()] = function;
2333
2334 // Set the parameter id's
2335 for (int p = 0; p < (int)parameters.size(); ++p) {
2336 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2337 // give a name too
2338 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2339 }
2340 }
2341}
2342
2343// Process all the initializers, while skipping the functions and link objects
2344void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2345{
2346 builder.setBuildPoint(shaderEntry->getLastBlock());
2347 for (int i = 0; i < (int)initializers.size(); ++i) {
2348 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2349 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2350
2351 // We're on a top-level node that's not a function. Treat as an initializer, whose
2352 // code goes into the beginning of main.
2353 initializer->traverse(this);
2354 }
2355 }
2356}
2357
2358// Process all the functions, while skipping initializers.
2359void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2360{
2361 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2362 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2363 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2364 node->traverse(this);
2365 }
2366}
2367
2368void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2369{
qining25262b32016-05-06 17:25:16 -04002370 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002371 // that called makeFunctions().
2372 spv::Function* function = functionMap[node->getName().c_str()];
2373 spv::Block* functionBlock = function->getEntryBlock();
2374 builder.setBuildPoint(functionBlock);
2375}
2376
Rex Xu04db3f52015-09-16 11:44:02 +08002377void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002378{
Rex Xufc618912015-09-09 16:42:49 +08002379 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002380
2381 glslang::TSampler sampler = {};
2382 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002383 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002384 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2385 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2386 }
2387
John Kessenich140f3df2015-06-26 16:58:36 -06002388 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2389 builder.clearAccessChain();
2390 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002391
2392 // Special case l-value operands
2393 bool lvalue = false;
2394 switch (node.getOp()) {
2395 case glslang::EOpImageAtomicAdd:
2396 case glslang::EOpImageAtomicMin:
2397 case glslang::EOpImageAtomicMax:
2398 case glslang::EOpImageAtomicAnd:
2399 case glslang::EOpImageAtomicOr:
2400 case glslang::EOpImageAtomicXor:
2401 case glslang::EOpImageAtomicExchange:
2402 case glslang::EOpImageAtomicCompSwap:
2403 if (i == 0)
2404 lvalue = true;
2405 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002406 case glslang::EOpSparseImageLoad:
2407 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2408 lvalue = true;
2409 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002410 case glslang::EOpSparseTexture:
2411 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2412 lvalue = true;
2413 break;
2414 case glslang::EOpSparseTextureClamp:
2415 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2416 lvalue = true;
2417 break;
2418 case glslang::EOpSparseTextureLod:
2419 case glslang::EOpSparseTextureOffset:
2420 if (i == 3)
2421 lvalue = true;
2422 break;
2423 case glslang::EOpSparseTextureFetch:
2424 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2425 lvalue = true;
2426 break;
2427 case glslang::EOpSparseTextureFetchOffset:
2428 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2429 lvalue = true;
2430 break;
2431 case glslang::EOpSparseTextureLodOffset:
2432 case glslang::EOpSparseTextureGrad:
2433 case glslang::EOpSparseTextureOffsetClamp:
2434 if (i == 4)
2435 lvalue = true;
2436 break;
2437 case glslang::EOpSparseTextureGradOffset:
2438 case glslang::EOpSparseTextureGradClamp:
2439 if (i == 5)
2440 lvalue = true;
2441 break;
2442 case glslang::EOpSparseTextureGradOffsetClamp:
2443 if (i == 6)
2444 lvalue = true;
2445 break;
2446 case glslang::EOpSparseTextureGather:
2447 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2448 lvalue = true;
2449 break;
2450 case glslang::EOpSparseTextureGatherOffset:
2451 case glslang::EOpSparseTextureGatherOffsets:
2452 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2453 lvalue = true;
2454 break;
Rex Xufc618912015-09-09 16:42:49 +08002455 default:
2456 break;
2457 }
2458
Rex Xu6b86d492015-09-16 17:48:22 +08002459 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002460 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002461 else
John Kessenich32cfd492016-02-02 12:37:46 -07002462 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002463 }
2464}
2465
John Kessenichfc51d282015-08-19 13:34:18 -06002466void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002467{
John Kessenichfc51d282015-08-19 13:34:18 -06002468 builder.clearAccessChain();
2469 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002470 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002471}
John Kessenich140f3df2015-06-26 16:58:36 -06002472
John Kessenichfc51d282015-08-19 13:34:18 -06002473spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2474{
Rex Xufc618912015-09-09 16:42:49 +08002475 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002476 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002477 }
2478
John Kessenichfc51d282015-08-19 13:34:18 -06002479 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002480 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2481 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2482 std::vector<spv::Id> arguments;
2483 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002484 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002485 else
2486 translateArguments(*node->getAsUnaryNode(), arguments);
2487 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2488
2489 spv::Builder::TextureParameters params = { };
2490 params.sampler = arguments[0];
2491
Rex Xu04db3f52015-09-16 11:44:02 +08002492 glslang::TCrackedTextureOp cracked;
2493 node->crackTexture(sampler, cracked);
2494
John Kessenichfc51d282015-08-19 13:34:18 -06002495 // Check for queries
2496 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002497 // a sampled image needs to have the image extracted first
2498 if (builder.isSampledImage(params.sampler))
2499 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002500 switch (node->getOp()) {
2501 case glslang::EOpImageQuerySize:
2502 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002503 if (arguments.size() > 1) {
2504 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002505 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002506 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002507 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002508 case glslang::EOpImageQuerySamples:
2509 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002510 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002511 case glslang::EOpTextureQueryLod:
2512 params.coords = arguments[1];
2513 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2514 case glslang::EOpTextureQueryLevels:
2515 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002516 case glslang::EOpSparseTexelsResident:
2517 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002518 default:
2519 assert(0);
2520 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002521 }
John Kessenich140f3df2015-06-26 16:58:36 -06002522 }
2523
Rex Xufc618912015-09-09 16:42:49 +08002524 // Check for image functions other than queries
2525 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002526 std::vector<spv::Id> operands;
2527 auto opIt = arguments.begin();
2528 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002529
2530 // Handle subpass operations
2531 // TODO: GLSL should change to have the "MS" only on the type rather than the
2532 // built-in function.
2533 if (cracked.subpass) {
2534 // add on the (0,0) coordinate
2535 spv::Id zero = builder.makeIntConstant(0);
2536 std::vector<spv::Id> comps;
2537 comps.push_back(zero);
2538 comps.push_back(zero);
2539 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2540 if (sampler.ms) {
2541 operands.push_back(spv::ImageOperandsSampleMask);
2542 operands.push_back(*(opIt++));
2543 }
2544 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2545 }
2546
John Kessenich56bab042015-09-16 10:54:31 -06002547 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002548 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002549 if (sampler.ms) {
2550 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002551 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002552 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002553 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2554 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002555 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002556 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002557 if (sampler.ms) {
2558 operands.push_back(*(opIt + 1));
2559 operands.push_back(spv::ImageOperandsSampleMask);
2560 operands.push_back(*opIt);
2561 } else
2562 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002563 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002564 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2565 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002566 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002567 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2568 builder.addCapability(spv::CapabilitySparseResidency);
2569 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2570 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2571
2572 if (sampler.ms) {
2573 operands.push_back(spv::ImageOperandsSampleMask);
2574 operands.push_back(*opIt++);
2575 }
2576
2577 // Create the return type that was a special structure
2578 spv::Id texelOut = *opIt;
2579 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2580 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2581 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2582
2583 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2584
2585 // Decode the return type
2586 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2587 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002588 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002589 // Process image atomic operations
2590
2591 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2592 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002593 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002594
Rex Xufc618912015-09-09 16:42:49 +08002595 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002596 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002597
2598 std::vector<spv::Id> operands;
2599 operands.push_back(pointer);
2600 for (; opIt != arguments.end(); ++opIt)
2601 operands.push_back(*opIt);
2602
Rex Xu04db3f52015-09-16 11:44:02 +08002603 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002604 }
2605 }
2606
2607 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002608 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002609 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2610
John Kessenichfc51d282015-08-19 13:34:18 -06002611 // check for bias argument
2612 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002613 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002614 int nonBiasArgCount = 2;
2615 if (cracked.offset)
2616 ++nonBiasArgCount;
2617 if (cracked.grad)
2618 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002619 if (cracked.lodClamp)
2620 ++nonBiasArgCount;
2621 if (sparse)
2622 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002623
2624 if ((int)arguments.size() > nonBiasArgCount)
2625 bias = true;
2626 }
2627
John Kessenicha5c33d62016-06-02 23:45:21 -06002628 // See if the sampler param should really be just the SPV image part
2629 if (cracked.fetch) {
2630 // a fetch needs to have the image extracted first
2631 if (builder.isSampledImage(params.sampler))
2632 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2633 }
2634
John Kessenichfc51d282015-08-19 13:34:18 -06002635 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002636
John Kessenichfc51d282015-08-19 13:34:18 -06002637 params.coords = arguments[1];
2638 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002639 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002640
2641 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002642 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002643 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002644 ++extraArgs;
2645 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002646 params.Dref = arguments[2];
2647 ++extraArgs;
2648 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002649 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002650 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002651 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002652 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002653 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002654 dRefComp = builder.getNumComponents(params.coords) - 1;
2655 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002656 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2657 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002658
2659 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002660 if (cracked.lod) {
2661 params.lod = arguments[2];
2662 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002663 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2664 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2665 noImplicitLod = true;
2666 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002667
2668 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002669 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002670 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002671 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002672 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002673
2674 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002675 if (cracked.grad) {
2676 params.gradX = arguments[2 + extraArgs];
2677 params.gradY = arguments[3 + extraArgs];
2678 extraArgs += 2;
2679 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002680
2681 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002682 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002683 params.offset = arguments[2 + extraArgs];
2684 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002685 } else if (cracked.offsets) {
2686 params.offsets = arguments[2 + extraArgs];
2687 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002688 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002689
2690 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002691 if (cracked.lodClamp) {
2692 params.lodClamp = arguments[2 + extraArgs];
2693 ++extraArgs;
2694 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002695
2696 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002697 if (sparse) {
2698 params.texelOut = arguments[2 + extraArgs];
2699 ++extraArgs;
2700 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002701
2702 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002703 if (bias) {
2704 params.bias = arguments[2 + extraArgs];
2705 ++extraArgs;
2706 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002707
2708 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002709 if (cracked.gather && ! sampler.shadow) {
2710 // default component is 0, if missing, otherwise an argument
2711 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002712 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002713 ++extraArgs;
2714 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002715 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002716 }
2717 }
John Kessenichfc51d282015-08-19 13:34:18 -06002718
John Kessenich65336482016-06-16 14:06:26 -06002719 // projective component (might not to move)
2720 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2721 // are divided by the last component of P."
2722 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2723 // unused components will appear after all used components."
2724 if (cracked.proj) {
2725 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2726 int projTargetComp;
2727 switch (sampler.dim) {
2728 case glslang::Esd1D: projTargetComp = 1; break;
2729 case glslang::Esd2D: projTargetComp = 2; break;
2730 case glslang::EsdRect: projTargetComp = 2; break;
2731 default: projTargetComp = projSourceComp; break;
2732 }
2733 // copy the projective coordinate if we have to
2734 if (projTargetComp != projSourceComp) {
2735 spv::Id projComp = builder.createCompositeExtract(params.coords,
2736 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2737 projSourceComp);
2738 params.coords = builder.createCompositeInsert(projComp, params.coords,
2739 builder.getTypeId(params.coords), projTargetComp);
2740 }
2741 }
2742
John Kessenich019f08f2016-02-15 15:40:42 -07002743 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002744}
2745
2746spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2747{
2748 // Grab the function's pointer from the previously created function
2749 spv::Function* function = functionMap[node->getName().c_str()];
2750 if (! function)
2751 return 0;
2752
2753 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2754 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2755
2756 // See comments in makeFunctions() for details about the semantics for parameter passing.
2757 //
2758 // These imply we need a four step process:
2759 // 1. Evaluate the arguments
2760 // 2. Allocate and make copies of in, out, and inout arguments
2761 // 3. Make the call
2762 // 4. Copy back the results
2763
2764 // 1. Evaluate the arguments
2765 std::vector<spv::Builder::AccessChain> lValues;
2766 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002767 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002768 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002769 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002770 // build l-value
2771 builder.clearAccessChain();
2772 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002773 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002774 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2775 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002776 // save l-value
2777 lValues.push_back(builder.getAccessChain());
2778 } else {
2779 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002780 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002781 }
2782 }
2783
2784 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2785 // copy the original into that space.
2786 //
2787 // Also, build up the list of actual arguments to pass in for the call
2788 int lValueCount = 0;
2789 int rValueCount = 0;
2790 std::vector<spv::Id> spvArgs;
2791 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002792 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002793 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002794 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002795 builder.setAccessChain(lValues[lValueCount]);
2796 arg = builder.accessChainGetLValue();
2797 ++lValueCount;
2798 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002799 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002800 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2801 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2802 // need to copy the input into output space
2803 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002804 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002805 builder.createStore(copy, arg);
2806 }
2807 ++lValueCount;
2808 } else {
2809 arg = rValues[rValueCount];
2810 ++rValueCount;
2811 }
2812 spvArgs.push_back(arg);
2813 }
2814
2815 // 3. Make the call.
2816 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002817 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002818
2819 // 4. Copy back out an "out" arguments.
2820 lValueCount = 0;
2821 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2822 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2823 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2824 spv::Id copy = builder.createLoad(spvArgs[a]);
2825 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002826 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002827 }
2828 ++lValueCount;
2829 }
2830 }
2831
2832 return result;
2833}
2834
2835// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002836spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2837 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002838 spv::Id typeId, spv::Id left, spv::Id right,
2839 glslang::TBasicType typeProxy, bool reduceComparison)
2840{
Rex Xu8ff43de2016-04-22 16:51:45 +08002841 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002842 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002843 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002844
2845 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002846 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002847 bool comparison = false;
2848
2849 switch (op) {
2850 case glslang::EOpAdd:
2851 case glslang::EOpAddAssign:
2852 if (isFloat)
2853 binOp = spv::OpFAdd;
2854 else
2855 binOp = spv::OpIAdd;
2856 break;
2857 case glslang::EOpSub:
2858 case glslang::EOpSubAssign:
2859 if (isFloat)
2860 binOp = spv::OpFSub;
2861 else
2862 binOp = spv::OpISub;
2863 break;
2864 case glslang::EOpMul:
2865 case glslang::EOpMulAssign:
2866 if (isFloat)
2867 binOp = spv::OpFMul;
2868 else
2869 binOp = spv::OpIMul;
2870 break;
2871 case glslang::EOpVectorTimesScalar:
2872 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002873 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002874 if (builder.isVector(right))
2875 std::swap(left, right);
2876 assert(builder.isScalar(right));
2877 needMatchingVectors = false;
2878 binOp = spv::OpVectorTimesScalar;
2879 } else
2880 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002881 break;
2882 case glslang::EOpVectorTimesMatrix:
2883 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002884 binOp = spv::OpVectorTimesMatrix;
2885 break;
2886 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002887 binOp = spv::OpMatrixTimesVector;
2888 break;
2889 case glslang::EOpMatrixTimesScalar:
2890 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002891 binOp = spv::OpMatrixTimesScalar;
2892 break;
2893 case glslang::EOpMatrixTimesMatrix:
2894 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002895 binOp = spv::OpMatrixTimesMatrix;
2896 break;
2897 case glslang::EOpOuterProduct:
2898 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002899 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002900 break;
2901
2902 case glslang::EOpDiv:
2903 case glslang::EOpDivAssign:
2904 if (isFloat)
2905 binOp = spv::OpFDiv;
2906 else if (isUnsigned)
2907 binOp = spv::OpUDiv;
2908 else
2909 binOp = spv::OpSDiv;
2910 break;
2911 case glslang::EOpMod:
2912 case glslang::EOpModAssign:
2913 if (isFloat)
2914 binOp = spv::OpFMod;
2915 else if (isUnsigned)
2916 binOp = spv::OpUMod;
2917 else
2918 binOp = spv::OpSMod;
2919 break;
2920 case glslang::EOpRightShift:
2921 case glslang::EOpRightShiftAssign:
2922 if (isUnsigned)
2923 binOp = spv::OpShiftRightLogical;
2924 else
2925 binOp = spv::OpShiftRightArithmetic;
2926 break;
2927 case glslang::EOpLeftShift:
2928 case glslang::EOpLeftShiftAssign:
2929 binOp = spv::OpShiftLeftLogical;
2930 break;
2931 case glslang::EOpAnd:
2932 case glslang::EOpAndAssign:
2933 binOp = spv::OpBitwiseAnd;
2934 break;
2935 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002936 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 binOp = spv::OpLogicalAnd;
2938 break;
2939 case glslang::EOpInclusiveOr:
2940 case glslang::EOpInclusiveOrAssign:
2941 binOp = spv::OpBitwiseOr;
2942 break;
2943 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002944 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002945 binOp = spv::OpLogicalOr;
2946 break;
2947 case glslang::EOpExclusiveOr:
2948 case glslang::EOpExclusiveOrAssign:
2949 binOp = spv::OpBitwiseXor;
2950 break;
2951 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002952 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002953 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955
2956 case glslang::EOpLessThan:
2957 case glslang::EOpGreaterThan:
2958 case glslang::EOpLessThanEqual:
2959 case glslang::EOpGreaterThanEqual:
2960 case glslang::EOpEqual:
2961 case glslang::EOpNotEqual:
2962 case glslang::EOpVectorEqual:
2963 case glslang::EOpVectorNotEqual:
2964 comparison = true;
2965 break;
2966 default:
2967 break;
2968 }
2969
John Kessenich7c1aa102015-10-15 13:29:11 -06002970 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002971 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002972 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002973 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002974 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002975
2976 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002977 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002978 builder.promoteScalar(precision, left, right);
2979
qining25262b32016-05-06 17:25:16 -04002980 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2981 addDecoration(result, noContraction);
2982 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002983 }
2984
2985 if (! comparison)
2986 return 0;
2987
John Kessenich7c1aa102015-10-15 13:29:11 -06002988 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002989
2990 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2991 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2992
John Kessenich22118352015-12-21 20:54:09 -07002993 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002994 }
2995
2996 switch (op) {
2997 case glslang::EOpLessThan:
2998 if (isFloat)
2999 binOp = spv::OpFOrdLessThan;
3000 else if (isUnsigned)
3001 binOp = spv::OpULessThan;
3002 else
3003 binOp = spv::OpSLessThan;
3004 break;
3005 case glslang::EOpGreaterThan:
3006 if (isFloat)
3007 binOp = spv::OpFOrdGreaterThan;
3008 else if (isUnsigned)
3009 binOp = spv::OpUGreaterThan;
3010 else
3011 binOp = spv::OpSGreaterThan;
3012 break;
3013 case glslang::EOpLessThanEqual:
3014 if (isFloat)
3015 binOp = spv::OpFOrdLessThanEqual;
3016 else if (isUnsigned)
3017 binOp = spv::OpULessThanEqual;
3018 else
3019 binOp = spv::OpSLessThanEqual;
3020 break;
3021 case glslang::EOpGreaterThanEqual:
3022 if (isFloat)
3023 binOp = spv::OpFOrdGreaterThanEqual;
3024 else if (isUnsigned)
3025 binOp = spv::OpUGreaterThanEqual;
3026 else
3027 binOp = spv::OpSGreaterThanEqual;
3028 break;
3029 case glslang::EOpEqual:
3030 case glslang::EOpVectorEqual:
3031 if (isFloat)
3032 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003033 else if (isBool)
3034 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 else
3036 binOp = spv::OpIEqual;
3037 break;
3038 case glslang::EOpNotEqual:
3039 case glslang::EOpVectorNotEqual:
3040 if (isFloat)
3041 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003042 else if (isBool)
3043 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003044 else
3045 binOp = spv::OpINotEqual;
3046 break;
3047 default:
3048 break;
3049 }
3050
qining25262b32016-05-06 17:25:16 -04003051 if (binOp != spv::OpNop) {
3052 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3053 addDecoration(result, noContraction);
3054 return builder.setPrecision(result, precision);
3055 }
John Kessenich140f3df2015-06-26 16:58:36 -06003056
3057 return 0;
3058}
3059
John Kessenich04bb8a02015-12-12 12:28:14 -07003060//
3061// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3062// These can be any of:
3063//
3064// matrix * scalar
3065// scalar * matrix
3066// matrix * matrix linear algebraic
3067// matrix * vector
3068// vector * matrix
3069// matrix * matrix componentwise
3070// matrix op matrix op in {+, -, /}
3071// matrix op scalar op in {+, -, /}
3072// scalar op matrix op in {+, -, /}
3073//
qining25262b32016-05-06 17:25:16 -04003074spv::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 -07003075{
3076 bool firstClass = true;
3077
3078 // First, handle first-class matrix operations (* and matrix/scalar)
3079 switch (op) {
3080 case spv::OpFDiv:
3081 if (builder.isMatrix(left) && builder.isScalar(right)) {
3082 // turn matrix / scalar into a multiply...
3083 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3084 op = spv::OpMatrixTimesScalar;
3085 } else
3086 firstClass = false;
3087 break;
3088 case spv::OpMatrixTimesScalar:
3089 if (builder.isMatrix(right))
3090 std::swap(left, right);
3091 assert(builder.isScalar(right));
3092 break;
3093 case spv::OpVectorTimesMatrix:
3094 assert(builder.isVector(left));
3095 assert(builder.isMatrix(right));
3096 break;
3097 case spv::OpMatrixTimesVector:
3098 assert(builder.isMatrix(left));
3099 assert(builder.isVector(right));
3100 break;
3101 case spv::OpMatrixTimesMatrix:
3102 assert(builder.isMatrix(left));
3103 assert(builder.isMatrix(right));
3104 break;
3105 default:
3106 firstClass = false;
3107 break;
3108 }
3109
qining25262b32016-05-06 17:25:16 -04003110 if (firstClass) {
3111 spv::Id result = builder.createBinOp(op, typeId, left, right);
3112 addDecoration(result, noContraction);
3113 return builder.setPrecision(result, precision);
3114 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003115
LoopDawg592860c2016-06-09 08:57:35 -06003116 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003117 // The result type of all of them is the same type as the (a) matrix operand.
3118 // The algorithm is to:
3119 // - break the matrix(es) into vectors
3120 // - smear any scalar to a vector
3121 // - do vector operations
3122 // - make a matrix out the vector results
3123 switch (op) {
3124 case spv::OpFAdd:
3125 case spv::OpFSub:
3126 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003127 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003128 case spv::OpFMul:
3129 {
3130 // one time set up...
3131 bool leftMat = builder.isMatrix(left);
3132 bool rightMat = builder.isMatrix(right);
3133 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3134 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3135 spv::Id scalarType = builder.getScalarTypeId(typeId);
3136 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3137 std::vector<spv::Id> results;
3138 spv::Id smearVec = spv::NoResult;
3139 if (builder.isScalar(left))
3140 smearVec = builder.smearScalar(precision, left, vecType);
3141 else if (builder.isScalar(right))
3142 smearVec = builder.smearScalar(precision, right, vecType);
3143
3144 // do each vector op
3145 for (unsigned int c = 0; c < numCols; ++c) {
3146 std::vector<unsigned int> indexes;
3147 indexes.push_back(c);
3148 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3149 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003150 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3151 addDecoration(result, noContraction);
3152 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003153 }
3154
3155 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003156 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003157 }
3158 default:
3159 assert(0);
3160 return spv::NoResult;
3161 }
3162}
3163
qining25262b32016-05-06 17:25:16 -04003164spv::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 -06003165{
3166 spv::Op unaryOp = spv::OpNop;
3167 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003168 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003169 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003170
3171 switch (op) {
3172 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003173 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003174 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003175 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003176 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003177 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003178 unaryOp = spv::OpSNegate;
3179 break;
3180
3181 case glslang::EOpLogicalNot:
3182 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003183 unaryOp = spv::OpLogicalNot;
3184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 case glslang::EOpBitwiseNot:
3186 unaryOp = spv::OpNot;
3187 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003188
John Kessenich140f3df2015-06-26 16:58:36 -06003189 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpTranspose:
3196 unaryOp = spv::OpTranspose;
3197 break;
3198
3199 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003200 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003201 break;
3202 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003204 break;
3205 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003206 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003207 break;
3208 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003209 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003210 break;
3211 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003212 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003213 break;
3214 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003215 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003216 break;
3217 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003218 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003219 break;
3220 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003221 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 break;
3223
3224 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003225 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003226 break;
3227 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003228 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003229 break;
3230 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 break;
3233 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003234 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003235 break;
3236 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003238 break;
3239 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003240 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242
3243 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003244 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003245 break;
3246 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003247 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003248 break;
3249
3250 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003251 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003252 break;
3253 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003254 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003255 break;
3256 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003257 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003258 break;
3259 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003260 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003261 break;
3262 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003263 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003264 break;
3265 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003266 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003267 break;
3268
3269 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003270 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003271 break;
3272 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003273 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003274 break;
3275 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003276 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003277 break;
3278 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003279 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 break;
3281 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003282 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 break;
3284 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003285 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003286 break;
3287
3288 case glslang::EOpIsNan:
3289 unaryOp = spv::OpIsNan;
3290 break;
3291 case glslang::EOpIsInf:
3292 unaryOp = spv::OpIsInf;
3293 break;
LoopDawg592860c2016-06-09 08:57:35 -06003294 case glslang::EOpIsFinite:
3295 unaryOp = spv::OpIsFinite;
3296 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003297
Rex Xucbc426e2015-12-15 16:03:10 +08003298 case glslang::EOpFloatBitsToInt:
3299 case glslang::EOpFloatBitsToUint:
3300 case glslang::EOpIntBitsToFloat:
3301 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003302 case glslang::EOpDoubleBitsToInt64:
3303 case glslang::EOpDoubleBitsToUint64:
3304 case glslang::EOpInt64BitsToDouble:
3305 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003306 unaryOp = spv::OpBitcast;
3307 break;
3308
John Kessenich140f3df2015-06-26 16:58:36 -06003309 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003310 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003311 break;
3312 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003319 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003322 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003323 break;
3324 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003325 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003327 case glslang::EOpPackSnorm4x8:
3328 libCall = spv::GLSLstd450PackSnorm4x8;
3329 break;
3330 case glslang::EOpUnpackSnorm4x8:
3331 libCall = spv::GLSLstd450UnpackSnorm4x8;
3332 break;
3333 case glslang::EOpPackUnorm4x8:
3334 libCall = spv::GLSLstd450PackUnorm4x8;
3335 break;
3336 case glslang::EOpUnpackUnorm4x8:
3337 libCall = spv::GLSLstd450UnpackUnorm4x8;
3338 break;
3339 case glslang::EOpPackDouble2x32:
3340 libCall = spv::GLSLstd450PackDouble2x32;
3341 break;
3342 case glslang::EOpUnpackDouble2x32:
3343 libCall = spv::GLSLstd450UnpackDouble2x32;
3344 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003345
Rex Xu8ff43de2016-04-22 16:51:45 +08003346 case glslang::EOpPackInt2x32:
3347 case glslang::EOpUnpackInt2x32:
3348 case glslang::EOpPackUint2x32:
3349 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003350 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003351 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3352 break;
3353
John Kessenich140f3df2015-06-26 16:58:36 -06003354 case glslang::EOpDPdx:
3355 unaryOp = spv::OpDPdx;
3356 break;
3357 case glslang::EOpDPdy:
3358 unaryOp = spv::OpDPdy;
3359 break;
3360 case glslang::EOpFwidth:
3361 unaryOp = spv::OpFwidth;
3362 break;
3363 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003364 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003365 unaryOp = spv::OpDPdxFine;
3366 break;
3367 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003368 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003369 unaryOp = spv::OpDPdyFine;
3370 break;
3371 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003372 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003373 unaryOp = spv::OpFwidthFine;
3374 break;
3375 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003376 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003377 unaryOp = spv::OpDPdxCoarse;
3378 break;
3379 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003380 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003381 unaryOp = spv::OpDPdyCoarse;
3382 break;
3383 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003384 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003385 unaryOp = spv::OpFwidthCoarse;
3386 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003387 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003388 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003389 libCall = spv::GLSLstd450InterpolateAtCentroid;
3390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003391 case glslang::EOpAny:
3392 unaryOp = spv::OpAny;
3393 break;
3394 case glslang::EOpAll:
3395 unaryOp = spv::OpAll;
3396 break;
3397
3398 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003399 if (isFloat)
3400 libCall = spv::GLSLstd450FAbs;
3401 else
3402 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003403 break;
3404 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003405 if (isFloat)
3406 libCall = spv::GLSLstd450FSign;
3407 else
3408 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410
John Kessenichfc51d282015-08-19 13:34:18 -06003411 case glslang::EOpAtomicCounterIncrement:
3412 case glslang::EOpAtomicCounterDecrement:
3413 case glslang::EOpAtomicCounter:
3414 {
3415 // Handle all of the atomics in one place, in createAtomicOperation()
3416 std::vector<spv::Id> operands;
3417 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003418 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003419 }
3420
John Kessenichfc51d282015-08-19 13:34:18 -06003421 case glslang::EOpBitFieldReverse:
3422 unaryOp = spv::OpBitReverse;
3423 break;
3424 case glslang::EOpBitCount:
3425 unaryOp = spv::OpBitCount;
3426 break;
3427 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003428 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003429 break;
3430 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003431 if (isUnsigned)
3432 libCall = spv::GLSLstd450FindUMsb;
3433 else
3434 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003435 break;
3436
Rex Xu574ab042016-04-14 16:53:07 +08003437 case glslang::EOpBallot:
3438 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003439 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003440 libCall = spv::GLSLstd450Bad;
3441 break;
3442
Rex Xu338b1852016-05-05 20:38:33 +08003443 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003444 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003445 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003446 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003447
John Kessenich140f3df2015-06-26 16:58:36 -06003448 default:
3449 return 0;
3450 }
3451
3452 spv::Id id;
3453 if (libCall >= 0) {
3454 std::vector<spv::Id> args;
3455 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003456 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003457 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003458 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003459 }
John Kessenich140f3df2015-06-26 16:58:36 -06003460
qining25262b32016-05-06 17:25:16 -04003461 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003462 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003463}
3464
John Kessenich7a53f762016-01-20 11:19:27 -07003465// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003466spv::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 -07003467{
3468 // Handle unary operations vector by vector.
3469 // The result type is the same type as the original type.
3470 // The algorithm is to:
3471 // - break the matrix into vectors
3472 // - apply the operation to each vector
3473 // - make a matrix out the vector results
3474
3475 // get the types sorted out
3476 int numCols = builder.getNumColumns(operand);
3477 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003478 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3479 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003480 std::vector<spv::Id> results;
3481
3482 // do each vector op
3483 for (int c = 0; c < numCols; ++c) {
3484 std::vector<unsigned int> indexes;
3485 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003486 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3487 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3488 addDecoration(destVec, noContraction);
3489 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003490 }
3491
3492 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003493 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003494}
3495
Rex Xu73e3ce72016-04-27 18:48:17 +08003496spv::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 -06003497{
3498 spv::Op convOp = spv::OpNop;
3499 spv::Id zero = 0;
3500 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003501 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003502
3503 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3504
3505 switch (op) {
3506 case glslang::EOpConvIntToBool:
3507 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003508 case glslang::EOpConvInt64ToBool:
3509 case glslang::EOpConvUint64ToBool:
3510 zero = (op == glslang::EOpConvInt64ToBool ||
3511 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003512 zero = makeSmearedConstant(zero, vectorSize);
3513 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3514
3515 case glslang::EOpConvFloatToBool:
3516 zero = builder.makeFloatConstant(0.0F);
3517 zero = makeSmearedConstant(zero, vectorSize);
3518 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3519
3520 case glslang::EOpConvDoubleToBool:
3521 zero = builder.makeDoubleConstant(0.0);
3522 zero = makeSmearedConstant(zero, vectorSize);
3523 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3524
3525 case glslang::EOpConvBoolToFloat:
3526 convOp = spv::OpSelect;
3527 zero = builder.makeFloatConstant(0.0);
3528 one = builder.makeFloatConstant(1.0);
3529 break;
3530 case glslang::EOpConvBoolToDouble:
3531 convOp = spv::OpSelect;
3532 zero = builder.makeDoubleConstant(0.0);
3533 one = builder.makeDoubleConstant(1.0);
3534 break;
3535 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003536 case glslang::EOpConvBoolToInt64:
3537 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3538 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003539 convOp = spv::OpSelect;
3540 break;
3541 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003542 case glslang::EOpConvBoolToUint64:
3543 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3544 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003545 convOp = spv::OpSelect;
3546 break;
3547
3548 case glslang::EOpConvIntToFloat:
3549 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003550 case glslang::EOpConvInt64ToFloat:
3551 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003552 convOp = spv::OpConvertSToF;
3553 break;
3554
3555 case glslang::EOpConvUintToFloat:
3556 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003557 case glslang::EOpConvUint64ToFloat:
3558 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003559 convOp = spv::OpConvertUToF;
3560 break;
3561
3562 case glslang::EOpConvDoubleToFloat:
3563 case glslang::EOpConvFloatToDouble:
3564 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003565 if (builder.isMatrixType(destType))
3566 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003567 break;
3568
3569 case glslang::EOpConvFloatToInt:
3570 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003571 case glslang::EOpConvFloatToInt64:
3572 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003573 convOp = spv::OpConvertFToS;
3574 break;
3575
3576 case glslang::EOpConvUintToInt:
3577 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003578 case glslang::EOpConvUint64ToInt64:
3579 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003580 if (builder.isInSpecConstCodeGenMode()) {
3581 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003582 zero = (op == glslang::EOpConvUintToInt64 ||
3583 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003584 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003585 // Use OpIAdd, instead of OpBitcast to do the conversion when
3586 // generating for OpSpecConstantOp instruction.
3587 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3588 }
3589 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003590 convOp = spv::OpBitcast;
3591 break;
3592
3593 case glslang::EOpConvFloatToUint:
3594 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003595 case glslang::EOpConvFloatToUint64:
3596 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003597 convOp = spv::OpConvertFToU;
3598 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003599
3600 case glslang::EOpConvIntToInt64:
3601 case glslang::EOpConvInt64ToInt:
3602 convOp = spv::OpSConvert;
3603 break;
3604
3605 case glslang::EOpConvUintToUint64:
3606 case glslang::EOpConvUint64ToUint:
3607 convOp = spv::OpUConvert;
3608 break;
3609
3610 case glslang::EOpConvIntToUint64:
3611 case glslang::EOpConvInt64ToUint:
3612 case glslang::EOpConvUint64ToInt:
3613 case glslang::EOpConvUintToInt64:
3614 // OpSConvert/OpUConvert + OpBitCast
3615 switch (op) {
3616 case glslang::EOpConvIntToUint64:
3617 convOp = spv::OpSConvert;
3618 type = builder.makeIntType(64);
3619 break;
3620 case glslang::EOpConvInt64ToUint:
3621 convOp = spv::OpSConvert;
3622 type = builder.makeIntType(32);
3623 break;
3624 case glslang::EOpConvUint64ToInt:
3625 convOp = spv::OpUConvert;
3626 type = builder.makeUintType(32);
3627 break;
3628 case glslang::EOpConvUintToInt64:
3629 convOp = spv::OpUConvert;
3630 type = builder.makeUintType(64);
3631 break;
3632 default:
3633 assert(0);
3634 break;
3635 }
3636
3637 if (vectorSize > 0)
3638 type = builder.makeVectorType(type, vectorSize);
3639
3640 operand = builder.createUnaryOp(convOp, type, operand);
3641
3642 if (builder.isInSpecConstCodeGenMode()) {
3643 // Build zero scalar or vector for OpIAdd.
3644 zero = (op == glslang::EOpConvIntToUint64 ||
3645 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3646 zero = makeSmearedConstant(zero, vectorSize);
3647 // Use OpIAdd, instead of OpBitcast to do the conversion when
3648 // generating for OpSpecConstantOp instruction.
3649 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3650 }
3651 // For normal run-time conversion instruction, use OpBitcast.
3652 convOp = spv::OpBitcast;
3653 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003654 default:
3655 break;
3656 }
3657
3658 spv::Id result = 0;
3659 if (convOp == spv::OpNop)
3660 return result;
3661
3662 if (convOp == spv::OpSelect) {
3663 zero = makeSmearedConstant(zero, vectorSize);
3664 one = makeSmearedConstant(one, vectorSize);
3665 result = builder.createTriOp(convOp, destType, operand, one, zero);
3666 } else
3667 result = builder.createUnaryOp(convOp, destType, operand);
3668
John Kessenich32cfd492016-02-02 12:37:46 -07003669 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003670}
3671
3672spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3673{
3674 if (vectorSize == 0)
3675 return constant;
3676
3677 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3678 std::vector<spv::Id> components;
3679 for (int c = 0; c < vectorSize; ++c)
3680 components.push_back(constant);
3681 return builder.makeCompositeConstant(vectorTypeId, components);
3682}
3683
John Kessenich426394d2015-07-23 10:22:48 -06003684// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003685spv::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 -06003686{
3687 spv::Op opCode = spv::OpNop;
3688
3689 switch (op) {
3690 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003691 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003692 opCode = spv::OpAtomicIAdd;
3693 break;
3694 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003695 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003696 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003697 break;
3698 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003699 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003700 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003701 break;
3702 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003703 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003704 opCode = spv::OpAtomicAnd;
3705 break;
3706 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003707 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003708 opCode = spv::OpAtomicOr;
3709 break;
3710 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003711 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003712 opCode = spv::OpAtomicXor;
3713 break;
3714 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003715 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003716 opCode = spv::OpAtomicExchange;
3717 break;
3718 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003719 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003720 opCode = spv::OpAtomicCompareExchange;
3721 break;
3722 case glslang::EOpAtomicCounterIncrement:
3723 opCode = spv::OpAtomicIIncrement;
3724 break;
3725 case glslang::EOpAtomicCounterDecrement:
3726 opCode = spv::OpAtomicIDecrement;
3727 break;
3728 case glslang::EOpAtomicCounter:
3729 opCode = spv::OpAtomicLoad;
3730 break;
3731 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003732 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003733 break;
3734 }
3735
3736 // Sort out the operands
3737 // - mapping from glslang -> SPV
3738 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003739 // - compare-exchange swaps the value and comparator
3740 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003741 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3742 auto opIt = operands.begin(); // walk the glslang operands
3743 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003744 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3745 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3746 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003747 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3748 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003749 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003750 spvAtomicOperands.push_back(*(opIt + 1));
3751 spvAtomicOperands.push_back(*opIt);
3752 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003753 }
John Kessenich426394d2015-07-23 10:22:48 -06003754
John Kessenich3e60a6f2015-09-14 22:45:16 -06003755 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003756 for (; opIt != operands.end(); ++opIt)
3757 spvAtomicOperands.push_back(*opIt);
3758
3759 return builder.createOp(opCode, typeId, spvAtomicOperands);
3760}
3761
John Kessenich91cef522016-05-05 16:45:40 -06003762// Create group invocation operations.
3763spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3764{
3765 builder.addCapability(spv::CapabilityGroups);
3766
3767 std::vector<spv::Id> operands;
3768 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3769 operands.push_back(operand);
3770
3771 switch (op) {
3772 case glslang::EOpAnyInvocation:
3773 case glslang::EOpAllInvocations:
3774 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3775
3776 case glslang::EOpAllInvocationsEqual:
3777 {
3778 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3779 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3780
3781 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3782 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3783 }
3784 default:
3785 logger->missingFunctionality("invocation operation");
3786 return spv::NoResult;
3787 }
3788}
3789
John Kessenich5e4b1242015-08-06 22:53:06 -06003790spv::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 -06003791{
Rex Xu8ff43de2016-04-22 16:51:45 +08003792 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3794
John Kessenich140f3df2015-06-26 16:58:36 -06003795 spv::Op opCode = spv::OpNop;
3796 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003797 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003798 spv::Id typeId0 = 0;
3799 if (consumedOperands > 0)
3800 typeId0 = builder.getTypeId(operands[0]);
3801 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003802
3803 switch (op) {
3804 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003805 if (isFloat)
3806 libCall = spv::GLSLstd450FMin;
3807 else if (isUnsigned)
3808 libCall = spv::GLSLstd450UMin;
3809 else
3810 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003811 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003812 break;
3813 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003814 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003815 break;
3816 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 if (isFloat)
3818 libCall = spv::GLSLstd450FMax;
3819 else if (isUnsigned)
3820 libCall = spv::GLSLstd450UMax;
3821 else
3822 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003823 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003824 break;
3825 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 case glslang::EOpDot:
3829 opCode = spv::OpDot;
3830 break;
3831 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003832 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
3834
3835 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003836 if (isFloat)
3837 libCall = spv::GLSLstd450FClamp;
3838 else if (isUnsigned)
3839 libCall = spv::GLSLstd450UClamp;
3840 else
3841 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003842 builder.promoteScalar(precision, operands.front(), operands[1]);
3843 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003846 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3847 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003848 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003849 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003850 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003851 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003852 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003853 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003854 break;
3855 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003856 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003857 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003858 break;
3859 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003860 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003861 builder.promoteScalar(precision, operands[0], operands[2]);
3862 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003863 break;
3864
3865 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003866 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003867 break;
3868 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003869 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003870 break;
3871 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003872 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003873 break;
3874 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003875 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003876 break;
3877 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003878 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003879 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003880 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003881 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003882 libCall = spv::GLSLstd450InterpolateAtSample;
3883 break;
3884 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003885 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003886 libCall = spv::GLSLstd450InterpolateAtOffset;
3887 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003888 case glslang::EOpAddCarry:
3889 opCode = spv::OpIAddCarry;
3890 typeId = builder.makeStructResultType(typeId0, typeId0);
3891 consumedOperands = 2;
3892 break;
3893 case glslang::EOpSubBorrow:
3894 opCode = spv::OpISubBorrow;
3895 typeId = builder.makeStructResultType(typeId0, typeId0);
3896 consumedOperands = 2;
3897 break;
3898 case glslang::EOpUMulExtended:
3899 opCode = spv::OpUMulExtended;
3900 typeId = builder.makeStructResultType(typeId0, typeId0);
3901 consumedOperands = 2;
3902 break;
3903 case glslang::EOpIMulExtended:
3904 opCode = spv::OpSMulExtended;
3905 typeId = builder.makeStructResultType(typeId0, typeId0);
3906 consumedOperands = 2;
3907 break;
3908 case glslang::EOpBitfieldExtract:
3909 if (isUnsigned)
3910 opCode = spv::OpBitFieldUExtract;
3911 else
3912 opCode = spv::OpBitFieldSExtract;
3913 break;
3914 case glslang::EOpBitfieldInsert:
3915 opCode = spv::OpBitFieldInsert;
3916 break;
3917
3918 case glslang::EOpFma:
3919 libCall = spv::GLSLstd450Fma;
3920 break;
3921 case glslang::EOpFrexp:
3922 libCall = spv::GLSLstd450FrexpStruct;
3923 if (builder.getNumComponents(operands[0]) == 1)
3924 frexpIntType = builder.makeIntegerType(32, true);
3925 else
3926 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3927 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3928 consumedOperands = 1;
3929 break;
3930 case glslang::EOpLdexp:
3931 libCall = spv::GLSLstd450Ldexp;
3932 break;
3933
Rex Xu574ab042016-04-14 16:53:07 +08003934 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003935 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003936 libCall = spv::GLSLstd450Bad;
3937 break;
3938
John Kessenich140f3df2015-06-26 16:58:36 -06003939 default:
3940 return 0;
3941 }
3942
3943 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003944 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003945 // Use an extended instruction from the standard library.
3946 // Construct the call arguments, without modifying the original operands vector.
3947 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3948 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003949 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003950 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003951 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003952 case 0:
3953 // should all be handled by visitAggregate and createNoArgOperation
3954 assert(0);
3955 return 0;
3956 case 1:
3957 // should all be handled by createUnaryOperation
3958 assert(0);
3959 return 0;
3960 case 2:
3961 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3962 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003963 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003964 // anything 3 or over doesn't have l-value operands, so all should be consumed
3965 assert(consumedOperands == operands.size());
3966 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003967 break;
3968 }
3969 }
3970
John Kessenich55e7d112015-11-15 21:33:39 -07003971 // Decode the return types that were structures
3972 switch (op) {
3973 case glslang::EOpAddCarry:
3974 case glslang::EOpSubBorrow:
3975 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3976 id = builder.createCompositeExtract(id, typeId0, 0);
3977 break;
3978 case glslang::EOpUMulExtended:
3979 case glslang::EOpIMulExtended:
3980 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3981 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3982 break;
3983 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003984 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003985 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3986 id = builder.createCompositeExtract(id, typeId0, 0);
3987 break;
3988 default:
3989 break;
3990 }
3991
John Kessenich32cfd492016-02-02 12:37:46 -07003992 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003993}
3994
3995// Intrinsics with no arguments, no return value, and no precision.
3996spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3997{
3998 // TODO: get the barrier operands correct
3999
4000 switch (op) {
4001 case glslang::EOpEmitVertex:
4002 builder.createNoResultOp(spv::OpEmitVertex);
4003 return 0;
4004 case glslang::EOpEndPrimitive:
4005 builder.createNoResultOp(spv::OpEndPrimitive);
4006 return 0;
4007 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004009 return 0;
4010 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004012 return 0;
4013 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004015 return 0;
4016 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004017 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004018 return 0;
4019 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004020 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004021 return 0;
4022 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004023 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004024 return 0;
4025 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004026 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004027 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004028 case glslang::EOpAllMemoryBarrierWithGroupSync:
4029 // Control barrier with non-"None" semantic is also a memory barrier.
4030 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4031 return 0;
4032 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4033 // Control barrier with non-"None" semantic is also a memory barrier.
4034 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4035 return 0;
4036 case glslang::EOpWorkgroupMemoryBarrier:
4037 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4038 return 0;
4039 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4040 // Control barrier with non-"None" semantic is also a memory barrier.
4041 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4042 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004043 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004044 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004045 return 0;
4046 }
4047}
4048
4049spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4050{
John Kessenich2f273362015-07-18 22:34:27 -06004051 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004052 spv::Id id;
4053 if (symbolValues.end() != iter) {
4054 id = iter->second;
4055 return id;
4056 }
4057
4058 // it was not found, create it
4059 id = createSpvVariable(symbol);
4060 symbolValues[symbol->getId()] = id;
4061
Rex Xuc884b4a2016-06-29 15:03:44 +08004062 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004063 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004064 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004065 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004066 if (symbol->getType().getQualifier().hasSpecConstantId())
4067 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004068 if (symbol->getQualifier().hasIndex())
4069 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4070 if (symbol->getQualifier().hasComponent())
4071 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4072 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004073 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004074 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004076 if (symbol->getQualifier().hasXfbBuffer())
4077 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4078 if (symbol->getQualifier().hasXfbOffset())
4079 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4080 }
4081 }
4082
scygan2c864272016-05-18 18:09:17 +02004083 if (symbol->getQualifier().hasLocation())
4084 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004085 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004086 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004087 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004088 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004089 }
John Kessenich140f3df2015-06-26 16:58:36 -06004090 if (symbol->getQualifier().hasSet())
4091 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004092 else if (IsDescriptorResource(symbol->getType())) {
4093 // default to 0
4094 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4095 }
John Kessenich140f3df2015-06-26 16:58:36 -06004096 if (symbol->getQualifier().hasBinding())
4097 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004098 if (symbol->getQualifier().hasAttachment())
4099 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004100 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004101 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004102 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004104 if (symbol->getQualifier().hasXfbBuffer())
4105 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4106 }
4107
Rex Xu1da878f2016-02-21 20:59:01 +08004108 if (symbol->getType().isImage()) {
4109 std::vector<spv::Decoration> memory;
4110 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4111 for (unsigned int i = 0; i < memory.size(); ++i)
4112 addDecoration(id, memory[i]);
4113 }
4114
John Kessenich140f3df2015-06-26 16:58:36 -06004115 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004116 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004118 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004119
John Kessenich140f3df2015-06-26 16:58:36 -06004120 return id;
4121}
4122
John Kessenich55e7d112015-11-15 21:33:39 -07004123// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004124void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4125{
4126 if (dec != spv::BadValue)
4127 builder.addDecoration(id, dec);
4128}
4129
John Kessenich55e7d112015-11-15 21:33:39 -07004130// If 'dec' is valid, add a one-operand decoration to an object
4131void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4132{
4133 if (dec != spv::BadValue)
4134 builder.addDecoration(id, dec, value);
4135}
4136
4137// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004138void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4139{
4140 if (dec != spv::BadValue)
4141 builder.addMemberDecoration(id, (unsigned)member, dec);
4142}
4143
John Kessenich92187592016-02-01 13:45:25 -07004144// If 'dec' is valid, add a one-operand decoration to a struct member
4145void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4146{
4147 if (dec != spv::BadValue)
4148 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4149}
4150
John Kessenich55e7d112015-11-15 21:33:39 -07004151// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004152// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004153//
4154// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4155//
4156// Recursively walk the nodes. The nodes form a tree whose leaves are
4157// regular constants, which themselves are trees that createSpvConstant()
4158// recursively walks. So, this function walks the "top" of the tree:
4159// - emit specialization constant-building instructions for specConstant
4160// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004161spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004162{
John Kessenich7cc0e282016-03-20 00:46:02 -06004163 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004164
qining4f4bb812016-04-03 23:55:17 -04004165 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004166 if (! node.getQualifier().specConstant) {
4167 // hand off to the non-spec-constant path
4168 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4169 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004170 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004171 nextConst, false);
4172 }
4173
4174 // We now know we have a specialization constant to build
4175
John Kessenichd94c0032016-05-30 19:29:40 -06004176 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004177 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4178 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4179 std::vector<spv::Id> dimConstId;
4180 for (int dim = 0; dim < 3; ++dim) {
4181 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4182 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4183 if (specConst)
4184 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4185 }
4186 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4187 }
4188
4189 // An AST node labelled as specialization constant should be a symbol node.
4190 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4191 if (auto* sn = node.getAsSymbolNode()) {
4192 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004193 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4194 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4195 // will set the builder into spec constant op instruction generating mode.
4196 sub_tree->traverse(this);
4197 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004198 } else if (auto* const_union_array = &sn->getConstArray()){
4199 int nextConst = 0;
4200 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004201 }
4202 }
qining4f4bb812016-04-03 23:55:17 -04004203
4204 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4205 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004206 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004207 exit(1);
4208 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004209}
4210
John Kessenich140f3df2015-06-26 16:58:36 -06004211// Use 'consts' as the flattened glslang source of scalar constants to recursively
4212// build the aggregate SPIR-V constant.
4213//
4214// If there are not enough elements present in 'consts', 0 will be substituted;
4215// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4216//
qining08408382016-03-21 09:51:37 -04004217spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004218{
4219 // vector of constants for SPIR-V
4220 std::vector<spv::Id> spvConsts;
4221
4222 // Type is used for struct and array constants
4223 spv::Id typeId = convertGlslangToSpvType(glslangType);
4224
4225 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004226 glslang::TType elementType(glslangType, 0);
4227 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004228 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004229 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004230 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004231 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004232 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004233 } else if (glslangType.getStruct()) {
4234 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4235 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004236 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004237 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004238 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4239 bool zero = nextConst >= consts.size();
4240 switch (glslangType.getBasicType()) {
4241 case glslang::EbtInt:
4242 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4243 break;
4244 case glslang::EbtUint:
4245 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4246 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004247 case glslang::EbtInt64:
4248 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4249 break;
4250 case glslang::EbtUint64:
4251 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4252 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004253 case glslang::EbtFloat:
4254 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4255 break;
4256 case glslang::EbtDouble:
4257 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4258 break;
4259 case glslang::EbtBool:
4260 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4261 break;
4262 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004264 break;
4265 }
4266 ++nextConst;
4267 }
4268 } else {
4269 // we have a non-aggregate (scalar) constant
4270 bool zero = nextConst >= consts.size();
4271 spv::Id scalar = 0;
4272 switch (glslangType.getBasicType()) {
4273 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004274 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004275 break;
4276 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004277 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004278 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004279 case glslang::EbtInt64:
4280 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4281 break;
4282 case glslang::EbtUint64:
4283 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4284 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004285 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004286 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004287 break;
4288 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004289 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004290 break;
4291 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004292 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004293 break;
4294 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004296 break;
4297 }
4298 ++nextConst;
4299 return scalar;
4300 }
4301
4302 return builder.makeCompositeConstant(typeId, spvConsts);
4303}
4304
John Kessenich7c1aa102015-10-15 13:29:11 -06004305// Return true if the node is a constant or symbol whose reading has no
4306// non-trivial observable cost or effect.
4307bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4308{
4309 // don't know what this is
4310 if (node == nullptr)
4311 return false;
4312
4313 // a constant is safe
4314 if (node->getAsConstantUnion() != nullptr)
4315 return true;
4316
4317 // not a symbol means non-trivial
4318 if (node->getAsSymbolNode() == nullptr)
4319 return false;
4320
4321 // a symbol, depends on what's being read
4322 switch (node->getType().getQualifier().storage) {
4323 case glslang::EvqTemporary:
4324 case glslang::EvqGlobal:
4325 case glslang::EvqIn:
4326 case glslang::EvqInOut:
4327 case glslang::EvqConst:
4328 case glslang::EvqConstReadOnly:
4329 case glslang::EvqUniform:
4330 return true;
4331 default:
4332 return false;
4333 }
qining25262b32016-05-06 17:25:16 -04004334}
John Kessenich7c1aa102015-10-15 13:29:11 -06004335
4336// A node is trivial if it is a single operation with no side effects.
4337// Error on the side of saying non-trivial.
4338// Return true if trivial.
4339bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4340{
4341 if (node == nullptr)
4342 return false;
4343
4344 // symbols and constants are trivial
4345 if (isTrivialLeaf(node))
4346 return true;
4347
4348 // otherwise, it needs to be a simple operation or one or two leaf nodes
4349
4350 // not a simple operation
4351 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4352 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4353 if (binaryNode == nullptr && unaryNode == nullptr)
4354 return false;
4355
4356 // not on leaf nodes
4357 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4358 return false;
4359
4360 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4361 return false;
4362 }
4363
4364 switch (node->getAsOperator()->getOp()) {
4365 case glslang::EOpLogicalNot:
4366 case glslang::EOpConvIntToBool:
4367 case glslang::EOpConvUintToBool:
4368 case glslang::EOpConvFloatToBool:
4369 case glslang::EOpConvDoubleToBool:
4370 case glslang::EOpEqual:
4371 case glslang::EOpNotEqual:
4372 case glslang::EOpLessThan:
4373 case glslang::EOpGreaterThan:
4374 case glslang::EOpLessThanEqual:
4375 case glslang::EOpGreaterThanEqual:
4376 case glslang::EOpIndexDirect:
4377 case glslang::EOpIndexDirectStruct:
4378 case glslang::EOpLogicalXor:
4379 case glslang::EOpAny:
4380 case glslang::EOpAll:
4381 return true;
4382 default:
4383 return false;
4384 }
4385}
4386
4387// Emit short-circuiting code, where 'right' is never evaluated unless
4388// the left side is true (for &&) or false (for ||).
4389spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4390{
4391 spv::Id boolTypeId = builder.makeBoolType();
4392
4393 // emit left operand
4394 builder.clearAccessChain();
4395 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004396 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004397
4398 // Operands to accumulate OpPhi operands
4399 std::vector<spv::Id> phiOperands;
4400 // accumulate left operand's phi information
4401 phiOperands.push_back(leftId);
4402 phiOperands.push_back(builder.getBuildPoint()->getId());
4403
4404 // Make the two kinds of operation symmetric with a "!"
4405 // || => emit "if (! left) result = right"
4406 // && => emit "if ( left) result = right"
4407 //
4408 // TODO: this runtime "not" for || could be avoided by adding functionality
4409 // to 'builder' to have an "else" without an "then"
4410 if (op == glslang::EOpLogicalOr)
4411 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4412
4413 // make an "if" based on the left value
4414 spv::Builder::If ifBuilder(leftId, builder);
4415
4416 // emit right operand as the "then" part of the "if"
4417 builder.clearAccessChain();
4418 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004419 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004420
4421 // accumulate left operand's phi information
4422 phiOperands.push_back(rightId);
4423 phiOperands.push_back(builder.getBuildPoint()->getId());
4424
4425 // finish the "if"
4426 ifBuilder.makeEndIf();
4427
4428 // phi together the two results
4429 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4430}
4431
John Kessenich140f3df2015-06-26 16:58:36 -06004432}; // end anonymous namespace
4433
4434namespace glslang {
4435
John Kessenich68d78fd2015-07-12 19:28:10 -06004436void GetSpirvVersion(std::string& version)
4437{
John Kessenich9e55f632015-07-15 10:03:39 -06004438 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004439 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004440 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004441 version = buf;
4442}
4443
John Kessenich140f3df2015-06-26 16:58:36 -06004444// Write SPIR-V out to a binary file
4445void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4446{
4447 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004448 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004449 for (int i = 0; i < (int)spirv.size(); ++i) {
4450 unsigned int word = spirv[i];
4451 out.write((const char*)&word, 4);
4452 }
4453 out.close();
4454}
4455
4456//
4457// Set up the glslang traversal
4458//
4459void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4460{
Lei Zhang17535f72016-05-04 15:55:59 -04004461 spv::SpvBuildLogger logger;
4462 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004463}
4464
Lei Zhang17535f72016-05-04 15:55:59 -04004465void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004466{
John Kessenich140f3df2015-06-26 16:58:36 -06004467 TIntermNode* root = intermediate.getTreeRoot();
4468
4469 if (root == 0)
4470 return;
4471
4472 glslang::GetThreadPoolAllocator().push();
4473
Lei Zhang17535f72016-05-04 15:55:59 -04004474 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004475
4476 root->traverse(&it);
4477
4478 it.dumpSpv(spirv);
4479
4480 glslang::GetThreadPoolAllocator().pop();
4481}
4482
4483}; // end namespace glslang