blob: ea6b2b4611a32e4deb7058421a246867111c4772 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
88}
89
John Kessenich140f3df2015-06-26 16:58:36 -060090//
91// The main holder of information for translating glslang to SPIR-V.
92//
93// Derives from the AST walking base class.
94//
95class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
96public:
97 TGlslangToSpvTraverser(const glslang::TIntermediate*);
98 virtual ~TGlslangToSpvTraverser();
99
100 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
101 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
102 void visitConstantUnion(glslang::TIntermConstantUnion*);
103 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
104 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
105 void visitSymbol(glslang::TIntermSymbol* symbol);
106 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
107 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
108 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
109
John Kessenich7ba63412015-12-20 17:37:07 -0700110 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112protected:
John Kessenich5e801132016-02-15 11:09:46 -0700113 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700114 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -0700115 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600116 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
117 spv::Id getSampledType(const glslang::TSampler&);
118 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700119 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700120 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700121 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800122 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700123 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700124 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
125 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
126 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
129 void makeFunctions(const glslang::TIntermSequence&);
130 void makeGlobalInitializers(const glslang::TIntermSequence&);
131 void visitFunctions(const glslang::TIntermSequence&);
132 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800133 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600134 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
135 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
137
138 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700139 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800140 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700141 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
143 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800144 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
162 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
163 spv::Builder builder;
164 bool inMain;
165 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700166 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 -0700167 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600168 const glslang::TIntermediate* glslangIntermediate;
169 spv::Id stdBuiltins;
170
John Kessenich2f273362015-07-18 22:34:27 -0600171 std::unordered_map<int, spv::Id> symbolValues;
172 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
173 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700174 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600175 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 -0600176 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600177};
178
179//
180// Helper functions for translating glslang representations to SPIR-V enumerants.
181//
182
183// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700184spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600185{
John Kessenich66e2faf2016-03-12 18:34:36 -0700186 switch (source) {
187 case glslang::EShSourceGlsl:
188 switch (profile) {
189 case ENoProfile:
190 case ECoreProfile:
191 case ECompatibilityProfile:
192 return spv::SourceLanguageGLSL;
193 case EEsProfile:
194 return spv::SourceLanguageESSL;
195 default:
196 return spv::SourceLanguageUnknown;
197 }
198 case glslang::EShSourceHlsl:
199 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600200 default:
201 return spv::SourceLanguageUnknown;
202 }
203}
204
205// Translate glslang language (stage) to SPIR-V execution model.
206spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
207{
208 switch (stage) {
209 case EShLangVertex: return spv::ExecutionModelVertex;
210 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
211 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
212 case EShLangGeometry: return spv::ExecutionModelGeometry;
213 case EShLangFragment: return spv::ExecutionModelFragment;
214 case EShLangCompute: return spv::ExecutionModelGLCompute;
215 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600217 return spv::ExecutionModelFragment;
218 }
219}
220
221// Translate glslang type to SPIR-V storage class.
222spv::StorageClass TranslateStorageClass(const glslang::TType& type)
223{
224 if (type.getQualifier().isPipeInput())
225 return spv::StorageClassInput;
226 else if (type.getQualifier().isPipeOutput())
227 return spv::StorageClassOutput;
228 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700229 if (type.getQualifier().layoutPushConstant)
230 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600231 if (type.getBasicType() == glslang::EbtBlock)
232 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800233 else if (type.getBasicType() == glslang::EbtAtomicUint)
234 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 else
236 return spv::StorageClassUniformConstant;
237 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
238 } else {
239 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700240 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
241 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
243 case glslang::EvqTemporary: return spv::StorageClassFunction;
244 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700245 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600246 return spv::StorageClassFunction;
247 }
248 }
249}
250
251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
268// Translate glslang type to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
270{
271 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
279// Translate glslang type to SPIR-V block decorations.
280spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
281{
282 if (type.getBasicType() == glslang::EbtBlock) {
283 switch (type.getQualifier().storage) {
284 case glslang::EvqUniform: return spv::DecorationBlock;
285 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
286 case glslang::EvqVaryingIn: return spv::DecorationBlock;
287 case glslang::EvqVaryingOut: return spv::DecorationBlock;
288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 break;
291 }
292 }
293
294 return (spv::Decoration)spv::BadValue;
295}
296
Rex Xu1da878f2016-02-21 20:59:01 +0800297// Translate glslang type to SPIR-V memory decorations.
298void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
299{
300 if (qualifier.coherent)
301 memory.push_back(spv::DecorationCoherent);
302 if (qualifier.volatil)
303 memory.push_back(spv::DecorationVolatile);
304 if (qualifier.restrict)
305 memory.push_back(spv::DecorationRestrict);
306 if (qualifier.readonly)
307 memory.push_back(spv::DecorationNonWritable);
308 if (qualifier.writeonly)
309 memory.push_back(spv::DecorationNonReadable);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700313spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600314{
315 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700316 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600317 case glslang::ElmRowMajor:
318 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700319 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600320 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 default:
322 // opaque layouts don't need a majorness
323 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600324 }
325 } else {
326 switch (type.getBasicType()) {
327 default:
328 return (spv::Decoration)spv::BadValue;
329 break;
330 case glslang::EbtBlock:
331 switch (type.getQualifier().storage) {
332 case glslang::EvqUniform:
333 case glslang::EvqBuffer:
334 switch (type.getQualifier().layoutPacking) {
335 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600336 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
337 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600338 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600339 }
340 case glslang::EvqVaryingIn:
341 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700342 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return (spv::Decoration)spv::BadValue;
344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 return (spv::Decoration)spv::BadValue;
347 }
348 }
349 }
350}
351
352// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700353// Returns spv::Decoration(spv::BadValue) when no decoration
354// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700355spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600356{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700357 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700358 // Smooth decoration doesn't exist in SPIR-V 1.0
359 return (spv::Decoration)spv::BadValue;
360 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700361 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700363 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600364 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700365 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600366 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700369 else if (qualifier.sample) {
370 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600371 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700372 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600373 return (spv::Decoration)spv::BadValue;
374}
375
John Kessenich92187592016-02-01 13:45:25 -0700376// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700377spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600378{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationInvariant;
381 else
382 return (spv::Decoration)spv::BadValue;
383}
384
385// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700386spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600387{
388 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700389 case glslang::EbvPointSize:
390 switch (glslangIntermediate->getStage()) {
391 case EShLangGeometry:
392 builder.addCapability(spv::CapabilityGeometryPointSize);
393 break;
394 case EShLangTessControl:
395 case EShLangTessEvaluation:
396 builder.addCapability(spv::CapabilityTessellationPointSize);
397 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100398 default:
399 break;
John Kessenich92187592016-02-01 13:45:25 -0700400 }
401 return spv::BuiltInPointSize;
402
403 case glslang::EbvClipDistance:
404 builder.addCapability(spv::CapabilityClipDistance);
405 return spv::BuiltInClipDistance;
406
407 case glslang::EbvCullDistance:
408 builder.addCapability(spv::CapabilityCullDistance);
409 return spv::BuiltInCullDistance;
410
411 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500412 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700413 return spv::BuiltInViewportIndex;
414
John Kessenich5e801132016-02-15 11:09:46 -0700415 case glslang::EbvSampleId:
416 builder.addCapability(spv::CapabilitySampleRateShading);
417 return spv::BuiltInSampleId;
418
419 case glslang::EbvSamplePosition:
420 builder.addCapability(spv::CapabilitySampleRateShading);
421 return spv::BuiltInSamplePosition;
422
423 case glslang::EbvSampleMask:
424 builder.addCapability(spv::CapabilitySampleRateShading);
425 return spv::BuiltInSampleMask;
426
John Kessenich140f3df2015-06-26 16:58:36 -0600427 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600428 case glslang::EbvVertexId: return spv::BuiltInVertexId;
429 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700430 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
431 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600432 case glslang::EbvBaseVertex:
433 case glslang::EbvBaseInstance:
434 case glslang::EbvDrawId:
435 // TODO: Add SPIR-V builtin ID.
436 spv::MissingFunctionality("Draw parameters");
437 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600438 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
439 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
440 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600441 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
442 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
443 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
444 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
445 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
446 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
447 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600448 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
449 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
450 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
451 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
452 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
453 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
454 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
455 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
456 default: return (spv::BuiltIn)spv::BadValue;
457 }
458}
459
Rex Xufc618912015-09-09 16:42:49 +0800460// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700461spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800462{
463 assert(type.getBasicType() == glslang::EbtSampler);
464
John Kessenich5d0fa972016-02-15 11:57:00 -0700465 // Check for capabilities
466 switch (type.getQualifier().layoutFormat) {
467 case glslang::ElfRg32f:
468 case glslang::ElfRg16f:
469 case glslang::ElfR11fG11fB10f:
470 case glslang::ElfR16f:
471 case glslang::ElfRgba16:
472 case glslang::ElfRgb10A2:
473 case glslang::ElfRg16:
474 case glslang::ElfRg8:
475 case glslang::ElfR16:
476 case glslang::ElfR8:
477 case glslang::ElfRgba16Snorm:
478 case glslang::ElfRg16Snorm:
479 case glslang::ElfRg8Snorm:
480 case glslang::ElfR16Snorm:
481 case glslang::ElfR8Snorm:
482
483 case glslang::ElfRg32i:
484 case glslang::ElfRg16i:
485 case glslang::ElfRg8i:
486 case glslang::ElfR16i:
487 case glslang::ElfR8i:
488
489 case glslang::ElfRgb10a2ui:
490 case glslang::ElfRg32ui:
491 case glslang::ElfRg16ui:
492 case glslang::ElfRg8ui:
493 case glslang::ElfR16ui:
494 case glslang::ElfR8ui:
495 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
496 break;
497
498 default:
499 break;
500 }
501
502 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800503 switch (type.getQualifier().layoutFormat) {
504 case glslang::ElfNone: return spv::ImageFormatUnknown;
505 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
506 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
507 case glslang::ElfR32f: return spv::ImageFormatR32f;
508 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
509 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
510 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
511 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
512 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
513 case glslang::ElfR16f: return spv::ImageFormatR16f;
514 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
515 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
516 case glslang::ElfRg16: return spv::ImageFormatRg16;
517 case glslang::ElfRg8: return spv::ImageFormatRg8;
518 case glslang::ElfR16: return spv::ImageFormatR16;
519 case glslang::ElfR8: return spv::ImageFormatR8;
520 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
521 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
522 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
523 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
524 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
525 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
526 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
527 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
528 case glslang::ElfR32i: return spv::ImageFormatR32i;
529 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
530 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
531 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
532 case glslang::ElfR16i: return spv::ImageFormatR16i;
533 case glslang::ElfR8i: return spv::ImageFormatR8i;
534 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
535 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
536 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
537 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
538 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
539 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
540 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
541 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
542 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
543 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
544 default: return (spv::ImageFormat)spv::BadValue;
545 }
546}
547
John Kessenich6c292d32016-02-15 20:58:50 -0700548// Return whether or not the given type is something that should be tied to a
549// descriptor set.
550bool IsDescriptorResource(const glslang::TType& type)
551{
John Kessenichf7497e22016-03-08 21:36:22 -0700552 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700553 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700554 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700555
556 // non block...
557 // basically samplerXXX/subpass/sampler/texture are all included
558 // if they are the global-scope-class, not the function parameter
559 // (or local, if they ever exist) class.
560 if (type.getBasicType() == glslang::EbtSampler)
561 return type.getQualifier().isUniformOrBuffer();
562
563 // None of the above.
564 return false;
565}
566
John Kesseniche0b6cad2015-12-24 10:30:13 -0700567void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
568{
569 if (child.layoutMatrix == glslang::ElmNone)
570 child.layoutMatrix = parent.layoutMatrix;
571
572 if (parent.invariant)
573 child.invariant = true;
574 if (parent.nopersp)
575 child.nopersp = true;
576 if (parent.flat)
577 child.flat = true;
578 if (parent.centroid)
579 child.centroid = true;
580 if (parent.patch)
581 child.patch = true;
582 if (parent.sample)
583 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800584 if (parent.coherent)
585 child.coherent = true;
586 if (parent.volatil)
587 child.volatil = true;
588 if (parent.restrict)
589 child.restrict = true;
590 if (parent.readonly)
591 child.readonly = true;
592 if (parent.writeonly)
593 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700594}
595
596bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
597{
John Kessenich7b9fa252016-01-21 18:56:57 -0700598 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700599 // - struct members can inherit from a struct declaration
600 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
601 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700602 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700603}
604
John Kessenich140f3df2015-06-26 16:58:36 -0600605//
606// Implement the TGlslangToSpvTraverser class.
607//
608
609TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
610 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700611 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600612 inMain(false), mainTerminated(false), linkageOnly(false),
613 glslangIntermediate(glslangIntermediate)
614{
615 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
616
617 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700618 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600619 stdBuiltins = builder.import("GLSL.std.450");
620 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700621 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
622 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600623
624 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600625 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
626 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600627 builder.addSourceExtension(it->c_str());
628
629 // Add the top-level modes for this shader.
630
John Kessenich92187592016-02-01 13:45:25 -0700631 if (glslangIntermediate->getXfbMode()) {
632 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700634 }
John Kessenich140f3df2015-06-26 16:58:36 -0600635
636 unsigned int mode;
637 switch (glslangIntermediate->getStage()) {
638 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600639 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600640 break;
641
642 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600643 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600644 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
645 break;
646
647 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600648 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600649 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700650 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
651 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
652 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600653 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655 if (mode != spv::BadValue)
656 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
657
John Kesseniche6903322015-10-13 16:29:02 -0600658 switch (glslangIntermediate->getVertexSpacing()) {
659 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
660 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
661 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
662 default: mode = spv::BadValue; break;
663 }
664 if (mode != spv::BadValue)
665 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
666
667 switch (glslangIntermediate->getVertexOrder()) {
668 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
669 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
670 default: mode = spv::BadValue; break;
671 }
672 if (mode != spv::BadValue)
673 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
674
675 if (glslangIntermediate->getPointMode())
676 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600677 break;
678
679 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600680 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600681 switch (glslangIntermediate->getInputPrimitive()) {
682 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
683 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
684 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700685 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600686 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
687 default: mode = spv::BadValue; break;
688 }
689 if (mode != spv::BadValue)
690 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600691
John Kessenich140f3df2015-06-26 16:58:36 -0600692 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
693
694 switch (glslangIntermediate->getOutputPrimitive()) {
695 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
696 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
697 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
698 default: mode = spv::BadValue; break;
699 }
700 if (mode != spv::BadValue)
701 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
702 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
703 break;
704
705 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600706 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600707 if (glslangIntermediate->getPixelCenterInteger())
708 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600709
John Kessenich140f3df2015-06-26 16:58:36 -0600710 if (glslangIntermediate->getOriginUpperLeft())
711 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600712 else
713 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600714
715 if (glslangIntermediate->getEarlyFragmentTests())
716 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
717
718 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600719 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
720 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
721 default: mode = spv::BadValue; break;
722 }
723 if (mode != spv::BadValue)
724 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
725
726 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
727 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600728 break;
729
730 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600731 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600732 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
733 glslangIntermediate->getLocalSize(1),
734 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600735 break;
736
737 default:
738 break;
739 }
740
741}
742
John Kessenich7ba63412015-12-20 17:37:07 -0700743// Finish everything and dump
744void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
745{
746 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100747 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
748 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700749
qiningda397332016-03-09 19:54:03 -0500750 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700751 builder.dump(out);
752}
753
John Kessenich140f3df2015-06-26 16:58:36 -0600754TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
755{
756 if (! mainTerminated) {
757 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
758 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600759 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600760 }
761}
762
763//
764// Implement the traversal functions.
765//
766// Return true from interior nodes to have the external traversal
767// continue on to children. Return false if children were
768// already processed.
769//
770
771//
772// Symbols can turn into
773// - uniform/input reads
774// - output writes
775// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
776// - something simple that degenerates into the last bullet
777//
778void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
779{
qining75d1d802016-04-06 14:42:01 -0400780 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
781 if (symbol->getType().getQualifier().isSpecConstant())
782 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
783
John Kessenich140f3df2015-06-26 16:58:36 -0600784 // getSymbolId() will set up all the IO decorations on the first call.
785 // Formal function parameters were mapped during makeFunctions().
786 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700787
788 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
789 if (builder.isPointer(id)) {
790 spv::StorageClass sc = builder.getStorageClass(id);
791 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
792 iOSet.insert(id);
793 }
794
795 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700796 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600797 // Prepare to generate code for the access
798
799 // L-value chains will be computed left to right. We're on the symbol now,
800 // which is the left-most part of the access chain, so now is "clear" time,
801 // followed by setting the base.
802 builder.clearAccessChain();
803
804 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700805 // except for
806 // A) "const in" arguments to a function, which are an intermediate object.
807 // See comments in handleUserFunctionCall().
808 // B) Specialization constants (normal constant don't even come in as a variable),
809 // These are also pure R-values.
810 glslang::TQualifier qualifier = symbol->getQualifier();
811 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
812 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600813 builder.setAccessChainRValue(id);
814 else
815 builder.setAccessChainLValue(id);
816 }
817}
818
819bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
820{
qining40887662016-04-03 22:20:42 -0400821 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
822 if (node->getType().getQualifier().isSpecConstant())
823 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
824
John Kessenich140f3df2015-06-26 16:58:36 -0600825 // First, handle special cases
826 switch (node->getOp()) {
827 case glslang::EOpAssign:
828 case glslang::EOpAddAssign:
829 case glslang::EOpSubAssign:
830 case glslang::EOpMulAssign:
831 case glslang::EOpVectorTimesMatrixAssign:
832 case glslang::EOpVectorTimesScalarAssign:
833 case glslang::EOpMatrixTimesScalarAssign:
834 case glslang::EOpMatrixTimesMatrixAssign:
835 case glslang::EOpDivAssign:
836 case glslang::EOpModAssign:
837 case glslang::EOpAndAssign:
838 case glslang::EOpInclusiveOrAssign:
839 case glslang::EOpExclusiveOrAssign:
840 case glslang::EOpLeftShiftAssign:
841 case glslang::EOpRightShiftAssign:
842 // A bin-op assign "a += b" means the same thing as "a = a + b"
843 // where a is evaluated before b. For a simple assignment, GLSL
844 // says to evaluate the left before the right. So, always, left
845 // node then right node.
846 {
847 // get the left l-value, save it away
848 builder.clearAccessChain();
849 node->getLeft()->traverse(this);
850 spv::Builder::AccessChain lValue = builder.getAccessChain();
851
852 // evaluate the right
853 builder.clearAccessChain();
854 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700855 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600856
857 if (node->getOp() != glslang::EOpAssign) {
858 // the left is also an r-value
859 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700860 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600861
862 // do the operation
863 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
864 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
865 node->getType().getBasicType());
866
867 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700868 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 }
870
871 // store the result
872 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800873 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600874
875 // assignments are expressions having an rValue after they are evaluated...
876 builder.clearAccessChain();
877 builder.setAccessChainRValue(rValue);
878 }
879 return false;
880 case glslang::EOpIndexDirect:
881 case glslang::EOpIndexDirectStruct:
882 {
883 // Get the left part of the access chain.
884 node->getLeft()->traverse(this);
885
886 // Add the next element in the chain
887
John Kessenich55e7d112015-11-15 21:33:39 -0700888 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600889 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
890 // This may be, e.g., an anonymous block-member selection, which generally need
891 // index remapping due to hidden members in anonymous blocks.
892 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700893 assert(remapper.size() > 0);
894 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600895 }
896
897 if (! node->getLeft()->getType().isArray() &&
898 node->getLeft()->getType().isVector() &&
899 node->getOp() == glslang::EOpIndexDirect) {
900 // This is essentially a hard-coded vector swizzle of size 1,
901 // so short circuit the access-chain stuff with a swizzle.
902 std::vector<unsigned> swizzle;
903 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600904 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600905 } else {
906 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600907 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600908 }
909 }
910 return false;
911 case glslang::EOpIndexIndirect:
912 {
913 // Structure or array or vector indirection.
914 // Will use native SPIR-V access-chain for struct and array indirection;
915 // matrices are arrays of vectors, so will also work for a matrix.
916 // Will use the access chain's 'component' for variable index into a vector.
917
918 // This adapter is building access chains left to right.
919 // Set up the access chain to the left.
920 node->getLeft()->traverse(this);
921
922 // save it so that computing the right side doesn't trash it
923 spv::Builder::AccessChain partial = builder.getAccessChain();
924
925 // compute the next index in the chain
926 builder.clearAccessChain();
927 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700928 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600929
930 // restore the saved access chain
931 builder.setAccessChain(partial);
932
933 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600934 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600935 else
John Kessenichfa668da2015-09-13 14:46:30 -0600936 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600937 }
938 return false;
939 case glslang::EOpVectorSwizzle:
940 {
941 node->getLeft()->traverse(this);
942 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
943 std::vector<unsigned> swizzle;
944 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
945 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600946 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600949 case glslang::EOpLogicalOr:
950 case glslang::EOpLogicalAnd:
951 {
952
953 // These may require short circuiting, but can sometimes be done as straight
954 // binary operations. The right operand must be short circuited if it has
955 // side effects, and should probably be if it is complex.
956 if (isTrivial(node->getRight()->getAsTyped()))
957 break; // handle below as a normal binary operation
958 // otherwise, we need to do dynamic short circuiting on the right operand
959 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
960 builder.clearAccessChain();
961 builder.setAccessChainRValue(result);
962 }
963 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600964 default:
965 break;
966 }
967
968 // Assume generic binary op...
969
John Kessenich32cfd492016-02-02 12:37:46 -0700970 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600971 builder.clearAccessChain();
972 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700973 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600974
John Kessenich32cfd492016-02-02 12:37:46 -0700975 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600976 builder.clearAccessChain();
977 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700978 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600979
John Kessenich32cfd492016-02-02 12:37:46 -0700980 // get result
981 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
982 convertGlslangToSpvType(node->getType()), left, right,
983 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600984
John Kessenich50e57562015-12-21 21:21:11 -0700985 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600986 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700987 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700988 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600989 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600990 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600991 return false;
992 }
John Kessenich140f3df2015-06-26 16:58:36 -0600993}
994
995bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
996{
qining40887662016-04-03 22:20:42 -0400997 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
998 if (node->getType().getQualifier().isSpecConstant())
999 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1000
John Kessenichfc51d282015-08-19 13:34:18 -06001001 spv::Id result = spv::NoResult;
1002
1003 // try texturing first
1004 result = createImageTextureFunctionCall(node);
1005 if (result != spv::NoResult) {
1006 builder.clearAccessChain();
1007 builder.setAccessChainRValue(result);
1008
1009 return false; // done with this node
1010 }
1011
1012 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001013
1014 if (node->getOp() == glslang::EOpArrayLength) {
1015 // Quite special; won't want to evaluate the operand.
1016
1017 // Normal .length() would have been constant folded by the front-end.
1018 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001019 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001020 assert(node->getOperand()->getType().isRuntimeSizedArray());
1021 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1022 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001023 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1024 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001025
1026 builder.clearAccessChain();
1027 builder.setAccessChainRValue(length);
1028
1029 return false;
1030 }
1031
John Kessenichfc51d282015-08-19 13:34:18 -06001032 // Start by evaluating the operand
1033
John Kessenich140f3df2015-06-26 16:58:36 -06001034 builder.clearAccessChain();
1035 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001036
Rex Xufc618912015-09-09 16:42:49 +08001037 spv::Id operand = spv::NoResult;
1038
1039 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1040 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001041 node->getOp() == glslang::EOpAtomicCounter ||
1042 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001043 operand = builder.accessChainGetLValue(); // Special case l-value operands
1044 else
John Kessenich32cfd492016-02-02 12:37:46 -07001045 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001046
1047 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1048
1049 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001050 if (! result)
1051 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001052
1053 // if not, then possibly an operation
1054 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001055 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001056
1057 if (result) {
1058 builder.clearAccessChain();
1059 builder.setAccessChainRValue(result);
1060
1061 return false; // done with this node
1062 }
1063
1064 // it must be a special case, check...
1065 switch (node->getOp()) {
1066 case glslang::EOpPostIncrement:
1067 case glslang::EOpPostDecrement:
1068 case glslang::EOpPreIncrement:
1069 case glslang::EOpPreDecrement:
1070 {
1071 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001072 spv::Id one = 0;
1073 if (node->getBasicType() == glslang::EbtFloat)
1074 one = builder.makeFloatConstant(1.0F);
1075 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1076 one = builder.makeInt64Constant(1);
1077 else
1078 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001079 glslang::TOperator op;
1080 if (node->getOp() == glslang::EOpPreIncrement ||
1081 node->getOp() == glslang::EOpPostIncrement)
1082 op = glslang::EOpAdd;
1083 else
1084 op = glslang::EOpSub;
1085
1086 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001087 convertGlslangToSpvType(node->getType()), operand, one,
1088 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001089 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 // The result of operation is always stored, but conditionally the
1092 // consumed result. The consumed result is always an r-value.
1093 builder.accessChainStore(result);
1094 builder.clearAccessChain();
1095 if (node->getOp() == glslang::EOpPreIncrement ||
1096 node->getOp() == glslang::EOpPreDecrement)
1097 builder.setAccessChainRValue(result);
1098 else
1099 builder.setAccessChainRValue(operand);
1100 }
1101
1102 return false;
1103
1104 case glslang::EOpEmitStreamVertex:
1105 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1106 return false;
1107 case glslang::EOpEndStreamPrimitive:
1108 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1109 return false;
1110
1111 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001112 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001113 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001114 }
John Kessenich140f3df2015-06-26 16:58:36 -06001115}
1116
1117bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1118{
qining27e04a02016-04-14 16:40:20 -04001119 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1120 if (node->getType().getQualifier().isSpecConstant())
1121 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1122
John Kessenichfc51d282015-08-19 13:34:18 -06001123 spv::Id result = spv::NoResult;
1124
1125 // try texturing
1126 result = createImageTextureFunctionCall(node);
1127 if (result != spv::NoResult) {
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(result);
1130
1131 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001132 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001133 // "imageStore" is a special case, which has no result
1134 return false;
1135 }
John Kessenichfc51d282015-08-19 13:34:18 -06001136
John Kessenich140f3df2015-06-26 16:58:36 -06001137 glslang::TOperator binOp = glslang::EOpNull;
1138 bool reduceComparison = true;
1139 bool isMatrix = false;
1140 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001141 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001142
1143 assert(node->getOp());
1144
1145 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1146
1147 switch (node->getOp()) {
1148 case glslang::EOpSequence:
1149 {
1150 if (preVisit)
1151 ++sequenceDepth;
1152 else
1153 --sequenceDepth;
1154
1155 if (sequenceDepth == 1) {
1156 // If this is the parent node of all the functions, we want to see them
1157 // early, so all call points have actual SPIR-V functions to reference.
1158 // In all cases, still let the traverser visit the children for us.
1159 makeFunctions(node->getAsAggregate()->getSequence());
1160
1161 // Also, we want all globals initializers to go into the entry of main(), before
1162 // anything else gets there, so visit out of order, doing them all now.
1163 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1164
1165 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1166 // so do them manually.
1167 visitFunctions(node->getAsAggregate()->getSequence());
1168
1169 return false;
1170 }
1171
1172 return true;
1173 }
1174 case glslang::EOpLinkerObjects:
1175 {
1176 if (visit == glslang::EvPreVisit)
1177 linkageOnly = true;
1178 else
1179 linkageOnly = false;
1180
1181 return true;
1182 }
1183 case glslang::EOpComma:
1184 {
1185 // processing from left to right naturally leaves the right-most
1186 // lying around in the access chain
1187 glslang::TIntermSequence& glslangOperands = node->getSequence();
1188 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1189 glslangOperands[i]->traverse(this);
1190
1191 return false;
1192 }
1193 case glslang::EOpFunction:
1194 if (visit == glslang::EvPreVisit) {
1195 if (isShaderEntrypoint(node)) {
1196 inMain = true;
1197 builder.setBuildPoint(shaderEntry->getLastBlock());
1198 } else {
1199 handleFunctionEntry(node);
1200 }
1201 } else {
1202 if (inMain)
1203 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001204 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001205 inMain = false;
1206 }
1207
1208 return true;
1209 case glslang::EOpParameters:
1210 // Parameters will have been consumed by EOpFunction processing, but not
1211 // the body, so we still visited the function node's children, making this
1212 // child redundant.
1213 return false;
1214 case glslang::EOpFunctionCall:
1215 {
1216 if (node->isUserDefined())
1217 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001218 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1219 if (result) {
1220 builder.clearAccessChain();
1221 builder.setAccessChainRValue(result);
1222 } else
1223 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001224
1225 return false;
1226 }
1227 case glslang::EOpConstructMat2x2:
1228 case glslang::EOpConstructMat2x3:
1229 case glslang::EOpConstructMat2x4:
1230 case glslang::EOpConstructMat3x2:
1231 case glslang::EOpConstructMat3x3:
1232 case glslang::EOpConstructMat3x4:
1233 case glslang::EOpConstructMat4x2:
1234 case glslang::EOpConstructMat4x3:
1235 case glslang::EOpConstructMat4x4:
1236 case glslang::EOpConstructDMat2x2:
1237 case glslang::EOpConstructDMat2x3:
1238 case glslang::EOpConstructDMat2x4:
1239 case glslang::EOpConstructDMat3x2:
1240 case glslang::EOpConstructDMat3x3:
1241 case glslang::EOpConstructDMat3x4:
1242 case glslang::EOpConstructDMat4x2:
1243 case glslang::EOpConstructDMat4x3:
1244 case glslang::EOpConstructDMat4x4:
1245 isMatrix = true;
1246 // fall through
1247 case glslang::EOpConstructFloat:
1248 case glslang::EOpConstructVec2:
1249 case glslang::EOpConstructVec3:
1250 case glslang::EOpConstructVec4:
1251 case glslang::EOpConstructDouble:
1252 case glslang::EOpConstructDVec2:
1253 case glslang::EOpConstructDVec3:
1254 case glslang::EOpConstructDVec4:
1255 case glslang::EOpConstructBool:
1256 case glslang::EOpConstructBVec2:
1257 case glslang::EOpConstructBVec3:
1258 case glslang::EOpConstructBVec4:
1259 case glslang::EOpConstructInt:
1260 case glslang::EOpConstructIVec2:
1261 case glslang::EOpConstructIVec3:
1262 case glslang::EOpConstructIVec4:
1263 case glslang::EOpConstructUint:
1264 case glslang::EOpConstructUVec2:
1265 case glslang::EOpConstructUVec3:
1266 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001267 case glslang::EOpConstructInt64:
1268 case glslang::EOpConstructI64Vec2:
1269 case glslang::EOpConstructI64Vec3:
1270 case glslang::EOpConstructI64Vec4:
1271 case glslang::EOpConstructUint64:
1272 case glslang::EOpConstructU64Vec2:
1273 case glslang::EOpConstructU64Vec3:
1274 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001275 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001276 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001277 {
1278 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001279 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001280 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1281 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001282 if (node->getOp() == glslang::EOpConstructTextureSampler)
1283 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1284 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001285 std::vector<spv::Id> constituents;
1286 for (int c = 0; c < (int)arguments.size(); ++c)
1287 constituents.push_back(arguments[c]);
1288 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001289 } else if (isMatrix)
1290 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1291 else
1292 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001293
1294 builder.clearAccessChain();
1295 builder.setAccessChainRValue(constructed);
1296
1297 return false;
1298 }
1299
1300 // These six are component-wise compares with component-wise results.
1301 // Forward on to createBinaryOperation(), requesting a vector result.
1302 case glslang::EOpLessThan:
1303 case glslang::EOpGreaterThan:
1304 case glslang::EOpLessThanEqual:
1305 case glslang::EOpGreaterThanEqual:
1306 case glslang::EOpVectorEqual:
1307 case glslang::EOpVectorNotEqual:
1308 {
1309 // Map the operation to a binary
1310 binOp = node->getOp();
1311 reduceComparison = false;
1312 switch (node->getOp()) {
1313 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1314 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1315 default: binOp = node->getOp(); break;
1316 }
1317
1318 break;
1319 }
1320 case glslang::EOpMul:
1321 // compontent-wise matrix multiply
1322 binOp = glslang::EOpMul;
1323 break;
1324 case glslang::EOpOuterProduct:
1325 // two vectors multiplied to make a matrix
1326 binOp = glslang::EOpOuterProduct;
1327 break;
1328 case glslang::EOpDot:
1329 {
1330 // for scalar dot product, use multiply
1331 glslang::TIntermSequence& glslangOperands = node->getSequence();
1332 if (! glslangOperands[0]->getAsTyped()->isVector())
1333 binOp = glslang::EOpMul;
1334 break;
1335 }
1336 case glslang::EOpMod:
1337 // when an aggregate, this is the floating-point mod built-in function,
1338 // which can be emitted by the one in createBinaryOperation()
1339 binOp = glslang::EOpMod;
1340 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001341 case glslang::EOpEmitVertex:
1342 case glslang::EOpEndPrimitive:
1343 case glslang::EOpBarrier:
1344 case glslang::EOpMemoryBarrier:
1345 case glslang::EOpMemoryBarrierAtomicCounter:
1346 case glslang::EOpMemoryBarrierBuffer:
1347 case glslang::EOpMemoryBarrierImage:
1348 case glslang::EOpMemoryBarrierShared:
1349 case glslang::EOpGroupMemoryBarrier:
1350 noReturnValue = true;
1351 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1352 break;
1353
John Kessenich426394d2015-07-23 10:22:48 -06001354 case glslang::EOpAtomicAdd:
1355 case glslang::EOpAtomicMin:
1356 case glslang::EOpAtomicMax:
1357 case glslang::EOpAtomicAnd:
1358 case glslang::EOpAtomicOr:
1359 case glslang::EOpAtomicXor:
1360 case glslang::EOpAtomicExchange:
1361 case glslang::EOpAtomicCompSwap:
1362 atomic = true;
1363 break;
1364
John Kessenich140f3df2015-06-26 16:58:36 -06001365 default:
1366 break;
1367 }
1368
1369 //
1370 // See if it maps to a regular operation.
1371 //
John Kessenich140f3df2015-06-26 16:58:36 -06001372 if (binOp != glslang::EOpNull) {
1373 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1374 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1375 assert(left && right);
1376
1377 builder.clearAccessChain();
1378 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001379 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001380
1381 builder.clearAccessChain();
1382 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001383 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001384
1385 result = createBinaryOperation(binOp, precision,
1386 convertGlslangToSpvType(node->getType()), leftId, rightId,
1387 left->getType().getBasicType(), reduceComparison);
1388
1389 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001390 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393
1394 return false;
1395 }
1396
John Kessenich426394d2015-07-23 10:22:48 -06001397 //
1398 // Create the list of operands.
1399 //
John Kessenich140f3df2015-06-26 16:58:36 -06001400 glslang::TIntermSequence& glslangOperands = node->getSequence();
1401 std::vector<spv::Id> operands;
1402 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1403 builder.clearAccessChain();
1404 glslangOperands[arg]->traverse(this);
1405
1406 // special case l-value operands; there are just a few
1407 bool lvalue = false;
1408 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001409 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001410 case glslang::EOpModf:
1411 if (arg == 1)
1412 lvalue = true;
1413 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001414 case glslang::EOpInterpolateAtSample:
1415 case glslang::EOpInterpolateAtOffset:
1416 if (arg == 0)
1417 lvalue = true;
1418 break;
Rex Xud4782c12015-09-06 16:30:11 +08001419 case glslang::EOpAtomicAdd:
1420 case glslang::EOpAtomicMin:
1421 case glslang::EOpAtomicMax:
1422 case glslang::EOpAtomicAnd:
1423 case glslang::EOpAtomicOr:
1424 case glslang::EOpAtomicXor:
1425 case glslang::EOpAtomicExchange:
1426 case glslang::EOpAtomicCompSwap:
1427 if (arg == 0)
1428 lvalue = true;
1429 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001430 case glslang::EOpAddCarry:
1431 case glslang::EOpSubBorrow:
1432 if (arg == 2)
1433 lvalue = true;
1434 break;
1435 case glslang::EOpUMulExtended:
1436 case glslang::EOpIMulExtended:
1437 if (arg >= 2)
1438 lvalue = true;
1439 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001440 default:
1441 break;
1442 }
1443 if (lvalue)
1444 operands.push_back(builder.accessChainGetLValue());
1445 else
John Kessenich32cfd492016-02-02 12:37:46 -07001446 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001447 }
John Kessenich426394d2015-07-23 10:22:48 -06001448
1449 if (atomic) {
1450 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001451 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001452 } else {
1453 // Pass through to generic operations.
1454 switch (glslangOperands.size()) {
1455 case 0:
1456 result = createNoArgOperation(node->getOp());
1457 break;
1458 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001459 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001460 break;
1461 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001462 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001463 break;
1464 }
John Kessenich140f3df2015-06-26 16:58:36 -06001465 }
1466
1467 if (noReturnValue)
1468 return false;
1469
1470 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001471 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001472 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001473 } else {
1474 builder.clearAccessChain();
1475 builder.setAccessChainRValue(result);
1476 return false;
1477 }
1478}
1479
1480bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1481{
1482 // This path handles both if-then-else and ?:
1483 // The if-then-else has a node type of void, while
1484 // ?: has a non-void node type
1485 spv::Id result = 0;
1486 if (node->getBasicType() != glslang::EbtVoid) {
1487 // don't handle this as just on-the-fly temporaries, because there will be two names
1488 // and better to leave SSA to later passes
1489 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1490 }
1491
1492 // emit the condition before doing anything with selection
1493 node->getCondition()->traverse(this);
1494
1495 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001496 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001497
1498 if (node->getTrueBlock()) {
1499 // emit the "then" statement
1500 node->getTrueBlock()->traverse(this);
1501 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001502 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001503 }
1504
1505 if (node->getFalseBlock()) {
1506 ifBuilder.makeBeginElse();
1507 // emit the "else" statement
1508 node->getFalseBlock()->traverse(this);
1509 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001510 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001511 }
1512
1513 ifBuilder.makeEndIf();
1514
1515 if (result) {
1516 // GLSL only has r-values as the result of a :?, but
1517 // if we have an l-value, that can be more efficient if it will
1518 // become the base of a complex r-value expression, because the
1519 // next layer copies r-values into memory to use the access-chain mechanism
1520 builder.clearAccessChain();
1521 builder.setAccessChainLValue(result);
1522 }
1523
1524 return false;
1525}
1526
1527bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1528{
1529 // emit and get the condition before doing anything with switch
1530 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001531 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001532
1533 // browse the children to sort out code segments
1534 int defaultSegment = -1;
1535 std::vector<TIntermNode*> codeSegments;
1536 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1537 std::vector<int> caseValues;
1538 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1539 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1540 TIntermNode* child = *c;
1541 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001542 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001543 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001544 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001545 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1546 } else
1547 codeSegments.push_back(child);
1548 }
1549
1550 // handle the case where the last code segment is missing, due to no code
1551 // statements between the last case and the end of the switch statement
1552 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1553 (int)codeSegments.size() == defaultSegment)
1554 codeSegments.push_back(nullptr);
1555
1556 // make the switch statement
1557 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001558 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001559
1560 // emit all the code in the segments
1561 breakForLoop.push(false);
1562 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1563 builder.nextSwitchSegment(segmentBlocks, s);
1564 if (codeSegments[s])
1565 codeSegments[s]->traverse(this);
1566 else
1567 builder.addSwitchBreak();
1568 }
1569 breakForLoop.pop();
1570
1571 builder.endSwitch(segmentBlocks);
1572
1573 return false;
1574}
1575
1576void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1577{
1578 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001579 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001580
1581 builder.clearAccessChain();
1582 builder.setAccessChainRValue(constant);
1583}
1584
1585bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1586{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001587 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001588 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001589 // Spec requires back edges to target header blocks, and every header block
1590 // must dominate its merge block. Make a header block first to ensure these
1591 // conditions are met. By definition, it will contain OpLoopMerge, followed
1592 // by a block-ending branch. But we don't want to put any other body/test
1593 // instructions in it, since the body/test may have arbitrary instructions,
1594 // including merges of its own.
1595 builder.setBuildPoint(&blocks.head);
1596 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001597 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001598 spv::Block& test = builder.makeNewBlock();
1599 builder.createBranch(&test);
1600
1601 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001602 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001603 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001604 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001605 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1606
1607 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001608 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001609 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001610 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001611 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001612 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001613
1614 builder.setBuildPoint(&blocks.continue_target);
1615 if (node->getTerminal())
1616 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001617 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001618 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001619 builder.createBranch(&blocks.body);
1620
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001621 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001622 builder.setBuildPoint(&blocks.body);
1623 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001624 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001625 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001626 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001627
1628 builder.setBuildPoint(&blocks.continue_target);
1629 if (node->getTerminal())
1630 node->getTerminal()->traverse(this);
1631 if (node->getTest()) {
1632 node->getTest()->traverse(this);
1633 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001634 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001635 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001636 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001637 // TODO: unless there was a break/return/discard instruction
1638 // somewhere in the body, this is an infinite loop, so we should
1639 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001640 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001641 }
John Kessenich140f3df2015-06-26 16:58:36 -06001642 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001643 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001644 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001645 return false;
1646}
1647
1648bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1649{
1650 if (node->getExpression())
1651 node->getExpression()->traverse(this);
1652
1653 switch (node->getFlowOp()) {
1654 case glslang::EOpKill:
1655 builder.makeDiscard();
1656 break;
1657 case glslang::EOpBreak:
1658 if (breakForLoop.top())
1659 builder.createLoopExit();
1660 else
1661 builder.addSwitchBreak();
1662 break;
1663 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001664 builder.createLoopContinue();
1665 break;
1666 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001667 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001668 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001669 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001670 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001671
1672 builder.clearAccessChain();
1673 break;
1674
1675 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001676 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001677 break;
1678 }
1679
1680 return false;
1681}
1682
1683spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1684{
1685 // First, steer off constants, which are not SPIR-V variables, but
1686 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001687 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001688 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001689 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001690 }
1691
1692 // Now, handle actual variables
1693 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1694 spv::Id spvType = convertGlslangToSpvType(node->getType());
1695
1696 const char* name = node->getName().c_str();
1697 if (glslang::IsAnonymous(name))
1698 name = "";
1699
1700 return builder.createVariable(storageClass, spvType, name);
1701}
1702
1703// Return type Id of the sampled type.
1704spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1705{
1706 switch (sampler.type) {
1707 case glslang::EbtFloat: return builder.makeFloatType(32);
1708 case glslang::EbtInt: return builder.makeIntType(32);
1709 case glslang::EbtUint: return builder.makeUintType(32);
1710 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001711 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001712 return builder.makeFloatType(32);
1713 }
1714}
1715
John Kessenich3ac051e2015-12-20 11:29:16 -07001716// Convert from a glslang type to an SPV type, by calling into a
1717// recursive version of this function. This establishes the inherited
1718// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001719spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1720{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001721 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001722}
1723
1724// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001725// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001726spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001727{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001728 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001729
1730 switch (type.getBasicType()) {
1731 case glslang::EbtVoid:
1732 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001733 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001734 break;
1735 case glslang::EbtFloat:
1736 spvType = builder.makeFloatType(32);
1737 break;
1738 case glslang::EbtDouble:
1739 spvType = builder.makeFloatType(64);
1740 break;
1741 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001742 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1743 // a 32-bit int where non-0 means true.
1744 if (explicitLayout != glslang::ElpNone)
1745 spvType = builder.makeUintType(32);
1746 else
1747 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001748 break;
1749 case glslang::EbtInt:
1750 spvType = builder.makeIntType(32);
1751 break;
1752 case glslang::EbtUint:
1753 spvType = builder.makeUintType(32);
1754 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001755 case glslang::EbtInt64:
1756 builder.addCapability(spv::CapabilityInt64);
1757 spvType = builder.makeIntType(64);
1758 break;
1759 case glslang::EbtUint64:
1760 builder.addCapability(spv::CapabilityInt64);
1761 spvType = builder.makeUintType(64);
1762 break;
John Kessenich426394d2015-07-23 10:22:48 -06001763 case glslang::EbtAtomicUint:
1764 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1765 spvType = builder.makeUintType(32);
1766 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001767 case glslang::EbtSampler:
1768 {
1769 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001770 if (sampler.sampler) {
1771 // pure sampler
1772 spvType = builder.makeSamplerType();
1773 } else {
1774 // an image is present, make its type
1775 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1776 sampler.image ? 2 : 1, TranslateImageFormat(type));
1777 if (sampler.combined) {
1778 // already has both image and sampler, make the combined type
1779 spvType = builder.makeSampledImageType(spvType);
1780 }
John Kessenich55e7d112015-11-15 21:33:39 -07001781 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001782 }
John Kessenich140f3df2015-06-26 16:58:36 -06001783 break;
1784 case glslang::EbtStruct:
1785 case glslang::EbtBlock:
1786 {
1787 // If we've seen this struct type, return it
1788 const glslang::TTypeList* glslangStruct = type.getStruct();
1789 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001790
1791 // Try to share structs for different layouts, but not yet for other
1792 // kinds of qualification (primarily not yet including interpolant qualification).
1793 if (! HasNonLayoutQualifiers(qualifier))
1794 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1795 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001796 break;
1797
1798 // else, we haven't seen it...
1799
1800 // Create a vector of struct types for SPIR-V to consume
1801 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1802 if (type.getBasicType() == glslang::EbtBlock)
1803 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001804 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001805 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1806 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1807 if (glslangType.hiddenMember()) {
1808 ++memberDelta;
1809 if (type.getBasicType() == glslang::EbtBlock)
1810 memberRemapper[glslangStruct][i] = -1;
1811 } else {
1812 if (type.getBasicType() == glslang::EbtBlock)
1813 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001814 // modify just this child's view of the qualifier
1815 glslang::TQualifier subQualifier = glslangType.getQualifier();
1816 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001817
1818 // manually inherit location; it's more complex
1819 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1820 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1821 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001822 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001823
1824 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001825 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001826 }
1827 }
1828
1829 // Make the SPIR-V type
1830 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001831 if (! HasNonLayoutQualifiers(qualifier))
1832 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001833
1834 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001835 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001836 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001837 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1838 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1839 int member = i;
1840 if (type.getBasicType() == glslang::EbtBlock)
1841 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001842
John Kesseniche0b6cad2015-12-24 10:30:13 -07001843 // modify just this child's view of the qualifier
1844 glslang::TQualifier subQualifier = glslangType.getQualifier();
1845 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001846
John Kessenich140f3df2015-06-26 16:58:36 -06001847 // using -1 above to indicate a hidden member
1848 if (member >= 0) {
1849 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001850 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001851 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001852 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1853 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001854
Rex Xu1da878f2016-02-21 20:59:01 +08001855 if (qualifier.storage == glslang::EvqBuffer) {
1856 std::vector<spv::Decoration> memory;
1857 TranslateMemoryDecoration(subQualifier, memory);
1858 for (unsigned int i = 0; i < memory.size(); ++i)
1859 addMemberDecoration(spvType, member, memory[i]);
1860 }
1861
John Kessenich09677482016-02-19 12:21:50 -07001862 // compute location decoration; tricky based on whether inheritance is at play
1863 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1864 // probably move to the linker stage of the front end proper, and just have the
1865 // answer sitting already distributed throughout the individual member locations.
1866 int location = -1; // will only decorate if present or inherited
1867 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1868 location = subQualifier.layoutLocation;
1869 else if (qualifier.hasLocation()) // inheritance
1870 location = qualifier.layoutLocation + locationOffset;
1871 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001872 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001873 if (location >= 0)
1874 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1875
1876 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001877 if (glslangType.getQualifier().hasComponent())
1878 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1879 if (glslangType.getQualifier().hasXfbOffset())
1880 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001881 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001882 // figure out what to do with offset, which is accumulating
1883 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001884 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001885 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001886 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001887 offset = nextOffset;
1888 }
John Kessenich140f3df2015-06-26 16:58:36 -06001889
John Kessenichf85e8062015-12-19 13:57:10 -07001890 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001892
John Kessenich140f3df2015-06-26 16:58:36 -06001893 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001894 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1895 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001896 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001897 }
1898 }
1899
1900 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001901 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001902 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001903 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001904 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001905 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001906 }
John Kessenich140f3df2015-06-26 16:58:36 -06001907 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001908 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001909 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001910 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001911 if (type.getQualifier().hasXfbBuffer())
1912 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1913 }
1914 }
1915 break;
1916 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001917 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001918 break;
1919 }
1920
1921 if (type.isMatrix())
1922 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1923 else {
1924 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1925 if (type.getVectorSize() > 1)
1926 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1927 }
1928
1929 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001930 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1931
John Kessenichc9a80832015-09-12 12:17:44 -06001932 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001933 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001934 // We need to decorate array strides for types needing explicit layout, except blocks.
1935 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001936 // Use a dummy glslang type for querying internal strides of
1937 // arrays of arrays, but using just a one-dimensional array.
1938 glslang::TType simpleArrayType(type, 0); // deference type of the array
1939 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1940 simpleArrayType.getArraySizes().dereference();
1941
1942 // Will compute the higher-order strides here, rather than making a whole
1943 // pile of types and doing repetitive recursion on their contents.
1944 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1945 }
John Kessenichf8842e52016-01-04 19:22:56 -07001946
1947 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001948 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001949 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001950 if (stride > 0)
1951 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001952 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001953 }
1954 } else {
1955 // single-dimensional array, and don't yet have stride
1956
John Kessenichf8842e52016-01-04 19:22:56 -07001957 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001958 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1959 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001960 }
John Kessenich31ed4832015-09-09 17:51:38 -06001961
John Kessenichc9a80832015-09-12 12:17:44 -06001962 // Do the outer dimension, which might not be known for a runtime-sized array
1963 if (type.isRuntimeSizedArray()) {
1964 spvType = builder.makeRuntimeArray(spvType);
1965 } else {
1966 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001967 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001968 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001969 if (stride > 0)
1970 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001971 }
1972
1973 return spvType;
1974}
1975
John Kessenich6c292d32016-02-15 20:58:50 -07001976// Turn the expression forming the array size into an id.
1977// This is not quite trivial, because of specialization constants.
1978// Sometimes, a raw constant is turned into an Id, and sometimes
1979// a specialization constant expression is.
1980spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1981{
1982 // First, see if this is sized with a node, meaning a specialization constant:
1983 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1984 if (specNode != nullptr) {
1985 builder.clearAccessChain();
1986 specNode->traverse(this);
1987 return accessChainLoad(specNode->getAsTyped()->getType());
1988 }
1989
1990 // Otherwise, need a compile-time (front end) size, get it:
1991 int size = arraySizes.getDimSize(dim);
1992 assert(size > 0);
1993 return builder.makeUintConstant(size);
1994}
1995
John Kessenich103bef92016-02-08 21:38:15 -07001996// Wrap the builder's accessChainLoad to:
1997// - localize handling of RelaxedPrecision
1998// - use the SPIR-V inferred type instead of another conversion of the glslang type
1999// (avoids unnecessary work and possible type punning for structures)
2000// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002001spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2002{
John Kessenich103bef92016-02-08 21:38:15 -07002003 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2004 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2005
2006 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002007 if (type.getBasicType() == glslang::EbtBool) {
2008 if (builder.isScalarType(nominalTypeId)) {
2009 // Conversion for bool
2010 spv::Id boolType = builder.makeBoolType();
2011 if (nominalTypeId != boolType)
2012 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2013 } else if (builder.isVectorType(nominalTypeId)) {
2014 // Conversion for bvec
2015 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2016 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2017 if (nominalTypeId != bvecType)
2018 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2019 }
2020 }
John Kessenich103bef92016-02-08 21:38:15 -07002021
2022 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002023}
2024
Rex Xu27253232016-02-23 17:51:09 +08002025// Wrap the builder's accessChainStore to:
2026// - do conversion of concrete to abstract type
2027void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2028{
2029 // Need to convert to abstract types when necessary
2030 if (type.getBasicType() == glslang::EbtBool) {
2031 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2032
2033 if (builder.isScalarType(nominalTypeId)) {
2034 // Conversion for bool
2035 spv::Id boolType = builder.makeBoolType();
2036 if (nominalTypeId != boolType) {
2037 spv::Id zero = builder.makeUintConstant(0);
2038 spv::Id one = builder.makeUintConstant(1);
2039 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2040 }
2041 } else if (builder.isVectorType(nominalTypeId)) {
2042 // Conversion for bvec
2043 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2044 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2045 if (nominalTypeId != bvecType) {
2046 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2047 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2048 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2049 }
2050 }
2051 }
2052
2053 builder.accessChainStore(rvalue);
2054}
2055
John Kessenichf85e8062015-12-19 13:57:10 -07002056// Decide whether or not this type should be
2057// decorated with offsets and strides, and if so
2058// whether std140 or std430 rules should be applied.
2059glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002060{
John Kessenichf85e8062015-12-19 13:57:10 -07002061 // has to be a block
2062 if (type.getBasicType() != glslang::EbtBlock)
2063 return glslang::ElpNone;
2064
2065 // has to be a uniform or buffer block
2066 if (type.getQualifier().storage != glslang::EvqUniform &&
2067 type.getQualifier().storage != glslang::EvqBuffer)
2068 return glslang::ElpNone;
2069
2070 // return the layout to use
2071 switch (type.getQualifier().layoutPacking) {
2072 case glslang::ElpStd140:
2073 case glslang::ElpStd430:
2074 return type.getQualifier().layoutPacking;
2075 default:
2076 return glslang::ElpNone;
2077 }
John Kessenich31ed4832015-09-09 17:51:38 -06002078}
2079
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002080// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002081int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002082{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002083 int size;
John Kessenich49987892015-12-29 17:11:44 -07002084 int stride;
2085 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002086
2087 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002088}
2089
John Kessenich49987892015-12-29 17:11:44 -07002090// 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 -07002091// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002092int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002093{
John Kessenich49987892015-12-29 17:11:44 -07002094 glslang::TType elementType;
2095 elementType.shallowCopy(matrixType);
2096 elementType.clearArraySizes();
2097
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002098 int size;
John Kessenich49987892015-12-29 17:11:44 -07002099 int stride;
2100 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2101
2102 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002103}
2104
John Kessenich5e4b1242015-08-06 22:53:06 -06002105// Given a member type of a struct, realign the current offset for it, and compute
2106// the next (not yet aligned) offset for the next member, which will get aligned
2107// on the next call.
2108// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2109// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2110// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002111void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002112 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002113{
2114 // this will get a positive value when deemed necessary
2115 nextOffset = -1;
2116
John Kessenich5e4b1242015-08-06 22:53:06 -06002117 // override anything in currentOffset with user-set offset
2118 if (memberType.getQualifier().hasOffset())
2119 currentOffset = memberType.getQualifier().layoutOffset;
2120
2121 // It could be that current linker usage in glslang updated all the layoutOffset,
2122 // in which case the following code does not matter. But, that's not quite right
2123 // once cross-compilation unit GLSL validation is done, as the original user
2124 // settings are needed in layoutOffset, and then the following will come into play.
2125
John Kessenichf85e8062015-12-19 13:57:10 -07002126 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002127 if (! memberType.getQualifier().hasOffset())
2128 currentOffset = -1;
2129
2130 return;
2131 }
2132
John Kessenichf85e8062015-12-19 13:57:10 -07002133 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002134 if (currentOffset < 0)
2135 currentOffset = 0;
2136
2137 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2138 // but possibly not yet correctly aligned.
2139
2140 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002141 int dummyStride;
2142 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002143 glslang::RoundToPow2(currentOffset, memberAlignment);
2144 nextOffset = currentOffset + memberSize;
2145}
2146
John Kessenich140f3df2015-06-26 16:58:36 -06002147bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2148{
John Kessenich4d65ee32016-03-12 18:17:47 -07002149 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002150 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002151 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002152}
2153
2154// Make all the functions, skeletally, without actually visiting their bodies.
2155void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2156{
2157 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2158 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2159 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2160 continue;
2161
2162 // We're on a user function. Set up the basic interface for the function now,
2163 // so that it's available to call.
2164 // Translating the body will happen later.
2165 //
2166 // Typically (except for a "const in" parameter), an address will be passed to the
2167 // function. What it is an address of varies:
2168 //
2169 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2170 // so that write needs to be to a copy, hence the address of a copy works.
2171 //
2172 // - "const in" parameters can just be the r-value, as no writes need occur.
2173 //
2174 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2175 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2176
2177 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002178 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2180
2181 for (int p = 0; p < (int)parameters.size(); ++p) {
2182 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2183 spv::Id typeId = convertGlslangToSpvType(paramType);
2184 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2185 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2186 else
2187 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002188 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002189 paramTypes.push_back(typeId);
2190 }
2191
2192 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002193 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2194 convertGlslangToSpvType(glslFunction->getType()),
2195 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002196
2197 // Track function to emit/call later
2198 functionMap[glslFunction->getName().c_str()] = function;
2199
2200 // Set the parameter id's
2201 for (int p = 0; p < (int)parameters.size(); ++p) {
2202 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2203 // give a name too
2204 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2205 }
2206 }
2207}
2208
2209// Process all the initializers, while skipping the functions and link objects
2210void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2211{
2212 builder.setBuildPoint(shaderEntry->getLastBlock());
2213 for (int i = 0; i < (int)initializers.size(); ++i) {
2214 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2215 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2216
2217 // We're on a top-level node that's not a function. Treat as an initializer, whose
2218 // code goes into the beginning of main.
2219 initializer->traverse(this);
2220 }
2221 }
2222}
2223
2224// Process all the functions, while skipping initializers.
2225void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2226{
2227 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2228 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2229 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2230 node->traverse(this);
2231 }
2232}
2233
2234void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2235{
2236 // SPIR-V functions should already be in the functionMap from the prepass
2237 // that called makeFunctions().
2238 spv::Function* function = functionMap[node->getName().c_str()];
2239 spv::Block* functionBlock = function->getEntryBlock();
2240 builder.setBuildPoint(functionBlock);
2241}
2242
Rex Xu04db3f52015-09-16 11:44:02 +08002243void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002244{
Rex Xufc618912015-09-09 16:42:49 +08002245 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002246
2247 glslang::TSampler sampler = {};
2248 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002249 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002250 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2251 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2252 }
2253
John Kessenich140f3df2015-06-26 16:58:36 -06002254 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2255 builder.clearAccessChain();
2256 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002257
2258 // Special case l-value operands
2259 bool lvalue = false;
2260 switch (node.getOp()) {
2261 case glslang::EOpImageAtomicAdd:
2262 case glslang::EOpImageAtomicMin:
2263 case glslang::EOpImageAtomicMax:
2264 case glslang::EOpImageAtomicAnd:
2265 case glslang::EOpImageAtomicOr:
2266 case glslang::EOpImageAtomicXor:
2267 case glslang::EOpImageAtomicExchange:
2268 case glslang::EOpImageAtomicCompSwap:
2269 if (i == 0)
2270 lvalue = true;
2271 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002272 case glslang::EOpSparseImageLoad:
2273 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2274 lvalue = true;
2275 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002276 case glslang::EOpSparseTexture:
2277 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2278 lvalue = true;
2279 break;
2280 case glslang::EOpSparseTextureClamp:
2281 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2282 lvalue = true;
2283 break;
2284 case glslang::EOpSparseTextureLod:
2285 case glslang::EOpSparseTextureOffset:
2286 if (i == 3)
2287 lvalue = true;
2288 break;
2289 case glslang::EOpSparseTextureFetch:
2290 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2291 lvalue = true;
2292 break;
2293 case glslang::EOpSparseTextureFetchOffset:
2294 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2295 lvalue = true;
2296 break;
2297 case glslang::EOpSparseTextureLodOffset:
2298 case glslang::EOpSparseTextureGrad:
2299 case glslang::EOpSparseTextureOffsetClamp:
2300 if (i == 4)
2301 lvalue = true;
2302 break;
2303 case glslang::EOpSparseTextureGradOffset:
2304 case glslang::EOpSparseTextureGradClamp:
2305 if (i == 5)
2306 lvalue = true;
2307 break;
2308 case glslang::EOpSparseTextureGradOffsetClamp:
2309 if (i == 6)
2310 lvalue = true;
2311 break;
2312 case glslang::EOpSparseTextureGather:
2313 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2314 lvalue = true;
2315 break;
2316 case glslang::EOpSparseTextureGatherOffset:
2317 case glslang::EOpSparseTextureGatherOffsets:
2318 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2319 lvalue = true;
2320 break;
Rex Xufc618912015-09-09 16:42:49 +08002321 default:
2322 break;
2323 }
2324
Rex Xu6b86d492015-09-16 17:48:22 +08002325 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002326 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002327 else
John Kessenich32cfd492016-02-02 12:37:46 -07002328 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002329 }
2330}
2331
John Kessenichfc51d282015-08-19 13:34:18 -06002332void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002333{
John Kessenichfc51d282015-08-19 13:34:18 -06002334 builder.clearAccessChain();
2335 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002336 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002337}
John Kessenich140f3df2015-06-26 16:58:36 -06002338
John Kessenichfc51d282015-08-19 13:34:18 -06002339spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2340{
Rex Xufc618912015-09-09 16:42:49 +08002341 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002342 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002343 }
2344
John Kessenichfc51d282015-08-19 13:34:18 -06002345 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002346 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2347 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2348 std::vector<spv::Id> arguments;
2349 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002350 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002351 else
2352 translateArguments(*node->getAsUnaryNode(), arguments);
2353 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2354
2355 spv::Builder::TextureParameters params = { };
2356 params.sampler = arguments[0];
2357
Rex Xu04db3f52015-09-16 11:44:02 +08002358 glslang::TCrackedTextureOp cracked;
2359 node->crackTexture(sampler, cracked);
2360
John Kessenichfc51d282015-08-19 13:34:18 -06002361 // Check for queries
2362 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002363 // a sampled image needs to have the image extracted first
2364 if (builder.isSampledImage(params.sampler))
2365 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002366 switch (node->getOp()) {
2367 case glslang::EOpImageQuerySize:
2368 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002369 if (arguments.size() > 1) {
2370 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002371 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002372 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002373 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002374 case glslang::EOpImageQuerySamples:
2375 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002376 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002377 case glslang::EOpTextureQueryLod:
2378 params.coords = arguments[1];
2379 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2380 case glslang::EOpTextureQueryLevels:
2381 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002382 case glslang::EOpSparseTexelsResident:
2383 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002384 default:
2385 assert(0);
2386 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 }
John Kessenich140f3df2015-06-26 16:58:36 -06002388 }
2389
Rex Xufc618912015-09-09 16:42:49 +08002390 // Check for image functions other than queries
2391 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002392 std::vector<spv::Id> operands;
2393 auto opIt = arguments.begin();
2394 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002395
2396 // Handle subpass operations
2397 // TODO: GLSL should change to have the "MS" only on the type rather than the
2398 // built-in function.
2399 if (cracked.subpass) {
2400 // add on the (0,0) coordinate
2401 spv::Id zero = builder.makeIntConstant(0);
2402 std::vector<spv::Id> comps;
2403 comps.push_back(zero);
2404 comps.push_back(zero);
2405 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2406 if (sampler.ms) {
2407 operands.push_back(spv::ImageOperandsSampleMask);
2408 operands.push_back(*(opIt++));
2409 }
2410 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2411 }
2412
John Kessenich56bab042015-09-16 10:54:31 -06002413 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002414 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002415 if (sampler.ms) {
2416 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002417 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002418 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002419 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2420 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002421 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002422 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002423 if (sampler.ms) {
2424 operands.push_back(*(opIt + 1));
2425 operands.push_back(spv::ImageOperandsSampleMask);
2426 operands.push_back(*opIt);
2427 } else
2428 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002429 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002430 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2431 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002432 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002433 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2434 builder.addCapability(spv::CapabilitySparseResidency);
2435 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2436 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2437
2438 if (sampler.ms) {
2439 operands.push_back(spv::ImageOperandsSampleMask);
2440 operands.push_back(*opIt++);
2441 }
2442
2443 // Create the return type that was a special structure
2444 spv::Id texelOut = *opIt;
2445 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2446 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2447 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2448
2449 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2450
2451 // Decode the return type
2452 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2453 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002454 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002455 // Process image atomic operations
2456
2457 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2458 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002459 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002460
Rex Xufc618912015-09-09 16:42:49 +08002461 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002462 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002463
2464 std::vector<spv::Id> operands;
2465 operands.push_back(pointer);
2466 for (; opIt != arguments.end(); ++opIt)
2467 operands.push_back(*opIt);
2468
Rex Xu04db3f52015-09-16 11:44:02 +08002469 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002470 }
2471 }
2472
2473 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002474 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002475 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2476
John Kessenichfc51d282015-08-19 13:34:18 -06002477 // check for bias argument
2478 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002479 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002480 int nonBiasArgCount = 2;
2481 if (cracked.offset)
2482 ++nonBiasArgCount;
2483 if (cracked.grad)
2484 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002485 if (cracked.lodClamp)
2486 ++nonBiasArgCount;
2487 if (sparse)
2488 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002489
2490 if ((int)arguments.size() > nonBiasArgCount)
2491 bias = true;
2492 }
2493
John Kessenichfc51d282015-08-19 13:34:18 -06002494 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002495
John Kessenichfc51d282015-08-19 13:34:18 -06002496 params.coords = arguments[1];
2497 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002498 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002499
2500 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002501 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002502 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002503 ++extraArgs;
2504 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002505 params.Dref = arguments[2];
2506 ++extraArgs;
2507 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002508 std::vector<spv::Id> indexes;
2509 int comp;
2510 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002511 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002512 else
2513 comp = builder.getNumComponents(params.coords) - 1;
2514 indexes.push_back(comp);
2515 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2516 }
2517 if (cracked.lod) {
2518 params.lod = arguments[2];
2519 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002520 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2521 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2522 noImplicitLod = true;
2523 }
2524 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002525 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002526 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002527 }
2528 if (cracked.grad) {
2529 params.gradX = arguments[2 + extraArgs];
2530 params.gradY = arguments[3 + extraArgs];
2531 extraArgs += 2;
2532 }
John Kessenich55e7d112015-11-15 21:33:39 -07002533 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002534 params.offset = arguments[2 + extraArgs];
2535 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002536 } else if (cracked.offsets) {
2537 params.offsets = arguments[2 + extraArgs];
2538 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002539 }
Rex Xu48edadf2015-12-31 16:11:41 +08002540 if (cracked.lodClamp) {
2541 params.lodClamp = arguments[2 + extraArgs];
2542 ++extraArgs;
2543 }
2544 if (sparse) {
2545 params.texelOut = arguments[2 + extraArgs];
2546 ++extraArgs;
2547 }
John Kessenichfc51d282015-08-19 13:34:18 -06002548 if (bias) {
2549 params.bias = arguments[2 + extraArgs];
2550 ++extraArgs;
2551 }
John Kessenich55e7d112015-11-15 21:33:39 -07002552 if (cracked.gather && ! sampler.shadow) {
2553 // default component is 0, if missing, otherwise an argument
2554 if (2 + extraArgs < (int)arguments.size()) {
2555 params.comp = arguments[2 + extraArgs];
2556 ++extraArgs;
2557 } else {
2558 params.comp = builder.makeIntConstant(0);
2559 }
2560 }
John Kessenichfc51d282015-08-19 13:34:18 -06002561
John Kessenich019f08f2016-02-15 15:40:42 -07002562 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002563}
2564
2565spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2566{
2567 // Grab the function's pointer from the previously created function
2568 spv::Function* function = functionMap[node->getName().c_str()];
2569 if (! function)
2570 return 0;
2571
2572 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2573 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2574
2575 // See comments in makeFunctions() for details about the semantics for parameter passing.
2576 //
2577 // These imply we need a four step process:
2578 // 1. Evaluate the arguments
2579 // 2. Allocate and make copies of in, out, and inout arguments
2580 // 3. Make the call
2581 // 4. Copy back the results
2582
2583 // 1. Evaluate the arguments
2584 std::vector<spv::Builder::AccessChain> lValues;
2585 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002586 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002587 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2588 // build l-value
2589 builder.clearAccessChain();
2590 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002591 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002592 // keep outputs as l-values, evaluate input-only as r-values
2593 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2594 // save l-value
2595 lValues.push_back(builder.getAccessChain());
2596 } else {
2597 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002598 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002599 }
2600 }
2601
2602 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2603 // copy the original into that space.
2604 //
2605 // Also, build up the list of actual arguments to pass in for the call
2606 int lValueCount = 0;
2607 int rValueCount = 0;
2608 std::vector<spv::Id> spvArgs;
2609 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2610 spv::Id arg;
2611 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2612 // need space to hold the copy
2613 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2614 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2615 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2616 // need to copy the input into output space
2617 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002618 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002619 builder.createStore(copy, arg);
2620 }
2621 ++lValueCount;
2622 } else {
2623 arg = rValues[rValueCount];
2624 ++rValueCount;
2625 }
2626 spvArgs.push_back(arg);
2627 }
2628
2629 // 3. Make the call.
2630 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002631 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002632
2633 // 4. Copy back out an "out" arguments.
2634 lValueCount = 0;
2635 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2636 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2637 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2638 spv::Id copy = builder.createLoad(spvArgs[a]);
2639 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002640 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002641 }
2642 ++lValueCount;
2643 }
2644 }
2645
2646 return result;
2647}
2648
2649// Translate AST operation to SPV operation, already having SPV-based operands/types.
2650spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2651 spv::Id typeId, spv::Id left, spv::Id right,
2652 glslang::TBasicType typeProxy, bool reduceComparison)
2653{
Rex Xu8ff43de2016-04-22 16:51:45 +08002654 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002655 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002656 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002657
2658 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002659 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002660 bool comparison = false;
2661
2662 switch (op) {
2663 case glslang::EOpAdd:
2664 case glslang::EOpAddAssign:
2665 if (isFloat)
2666 binOp = spv::OpFAdd;
2667 else
2668 binOp = spv::OpIAdd;
2669 break;
2670 case glslang::EOpSub:
2671 case glslang::EOpSubAssign:
2672 if (isFloat)
2673 binOp = spv::OpFSub;
2674 else
2675 binOp = spv::OpISub;
2676 break;
2677 case glslang::EOpMul:
2678 case glslang::EOpMulAssign:
2679 if (isFloat)
2680 binOp = spv::OpFMul;
2681 else
2682 binOp = spv::OpIMul;
2683 break;
2684 case glslang::EOpVectorTimesScalar:
2685 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002686 if (isFloat) {
2687 if (builder.isVector(right))
2688 std::swap(left, right);
2689 assert(builder.isScalar(right));
2690 needMatchingVectors = false;
2691 binOp = spv::OpVectorTimesScalar;
2692 } else
2693 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002694 break;
2695 case glslang::EOpVectorTimesMatrix:
2696 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002697 binOp = spv::OpVectorTimesMatrix;
2698 break;
2699 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002700 binOp = spv::OpMatrixTimesVector;
2701 break;
2702 case glslang::EOpMatrixTimesScalar:
2703 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002704 binOp = spv::OpMatrixTimesScalar;
2705 break;
2706 case glslang::EOpMatrixTimesMatrix:
2707 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002708 binOp = spv::OpMatrixTimesMatrix;
2709 break;
2710 case glslang::EOpOuterProduct:
2711 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002712 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002713 break;
2714
2715 case glslang::EOpDiv:
2716 case glslang::EOpDivAssign:
2717 if (isFloat)
2718 binOp = spv::OpFDiv;
2719 else if (isUnsigned)
2720 binOp = spv::OpUDiv;
2721 else
2722 binOp = spv::OpSDiv;
2723 break;
2724 case glslang::EOpMod:
2725 case glslang::EOpModAssign:
2726 if (isFloat)
2727 binOp = spv::OpFMod;
2728 else if (isUnsigned)
2729 binOp = spv::OpUMod;
2730 else
2731 binOp = spv::OpSMod;
2732 break;
2733 case glslang::EOpRightShift:
2734 case glslang::EOpRightShiftAssign:
2735 if (isUnsigned)
2736 binOp = spv::OpShiftRightLogical;
2737 else
2738 binOp = spv::OpShiftRightArithmetic;
2739 break;
2740 case glslang::EOpLeftShift:
2741 case glslang::EOpLeftShiftAssign:
2742 binOp = spv::OpShiftLeftLogical;
2743 break;
2744 case glslang::EOpAnd:
2745 case glslang::EOpAndAssign:
2746 binOp = spv::OpBitwiseAnd;
2747 break;
2748 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002749 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002750 binOp = spv::OpLogicalAnd;
2751 break;
2752 case glslang::EOpInclusiveOr:
2753 case glslang::EOpInclusiveOrAssign:
2754 binOp = spv::OpBitwiseOr;
2755 break;
2756 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002757 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002758 binOp = spv::OpLogicalOr;
2759 break;
2760 case glslang::EOpExclusiveOr:
2761 case glslang::EOpExclusiveOrAssign:
2762 binOp = spv::OpBitwiseXor;
2763 break;
2764 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002765 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002766 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002767 break;
2768
2769 case glslang::EOpLessThan:
2770 case glslang::EOpGreaterThan:
2771 case glslang::EOpLessThanEqual:
2772 case glslang::EOpGreaterThanEqual:
2773 case glslang::EOpEqual:
2774 case glslang::EOpNotEqual:
2775 case glslang::EOpVectorEqual:
2776 case glslang::EOpVectorNotEqual:
2777 comparison = true;
2778 break;
2779 default:
2780 break;
2781 }
2782
John Kessenich7c1aa102015-10-15 13:29:11 -06002783 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002784 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002785 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002786 if (builder.isMatrix(left) || builder.isMatrix(right))
2787 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002788
2789 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002790 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002791 builder.promoteScalar(precision, left, right);
2792
John Kessenich32cfd492016-02-02 12:37:46 -07002793 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002794 }
2795
2796 if (! comparison)
2797 return 0;
2798
John Kessenich7c1aa102015-10-15 13:29:11 -06002799 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002800
2801 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2802 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2803
John Kessenich22118352015-12-21 20:54:09 -07002804 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002805 }
2806
2807 switch (op) {
2808 case glslang::EOpLessThan:
2809 if (isFloat)
2810 binOp = spv::OpFOrdLessThan;
2811 else if (isUnsigned)
2812 binOp = spv::OpULessThan;
2813 else
2814 binOp = spv::OpSLessThan;
2815 break;
2816 case glslang::EOpGreaterThan:
2817 if (isFloat)
2818 binOp = spv::OpFOrdGreaterThan;
2819 else if (isUnsigned)
2820 binOp = spv::OpUGreaterThan;
2821 else
2822 binOp = spv::OpSGreaterThan;
2823 break;
2824 case glslang::EOpLessThanEqual:
2825 if (isFloat)
2826 binOp = spv::OpFOrdLessThanEqual;
2827 else if (isUnsigned)
2828 binOp = spv::OpULessThanEqual;
2829 else
2830 binOp = spv::OpSLessThanEqual;
2831 break;
2832 case glslang::EOpGreaterThanEqual:
2833 if (isFloat)
2834 binOp = spv::OpFOrdGreaterThanEqual;
2835 else if (isUnsigned)
2836 binOp = spv::OpUGreaterThanEqual;
2837 else
2838 binOp = spv::OpSGreaterThanEqual;
2839 break;
2840 case glslang::EOpEqual:
2841 case glslang::EOpVectorEqual:
2842 if (isFloat)
2843 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002844 else if (isBool)
2845 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 else
2847 binOp = spv::OpIEqual;
2848 break;
2849 case glslang::EOpNotEqual:
2850 case glslang::EOpVectorNotEqual:
2851 if (isFloat)
2852 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002853 else if (isBool)
2854 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002855 else
2856 binOp = spv::OpINotEqual;
2857 break;
2858 default:
2859 break;
2860 }
2861
John Kessenich32cfd492016-02-02 12:37:46 -07002862 if (binOp != spv::OpNop)
2863 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002864
2865 return 0;
2866}
2867
John Kessenich04bb8a02015-12-12 12:28:14 -07002868//
2869// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2870// These can be any of:
2871//
2872// matrix * scalar
2873// scalar * matrix
2874// matrix * matrix linear algebraic
2875// matrix * vector
2876// vector * matrix
2877// matrix * matrix componentwise
2878// matrix op matrix op in {+, -, /}
2879// matrix op scalar op in {+, -, /}
2880// scalar op matrix op in {+, -, /}
2881//
2882spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2883{
2884 bool firstClass = true;
2885
2886 // First, handle first-class matrix operations (* and matrix/scalar)
2887 switch (op) {
2888 case spv::OpFDiv:
2889 if (builder.isMatrix(left) && builder.isScalar(right)) {
2890 // turn matrix / scalar into a multiply...
2891 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2892 op = spv::OpMatrixTimesScalar;
2893 } else
2894 firstClass = false;
2895 break;
2896 case spv::OpMatrixTimesScalar:
2897 if (builder.isMatrix(right))
2898 std::swap(left, right);
2899 assert(builder.isScalar(right));
2900 break;
2901 case spv::OpVectorTimesMatrix:
2902 assert(builder.isVector(left));
2903 assert(builder.isMatrix(right));
2904 break;
2905 case spv::OpMatrixTimesVector:
2906 assert(builder.isMatrix(left));
2907 assert(builder.isVector(right));
2908 break;
2909 case spv::OpMatrixTimesMatrix:
2910 assert(builder.isMatrix(left));
2911 assert(builder.isMatrix(right));
2912 break;
2913 default:
2914 firstClass = false;
2915 break;
2916 }
2917
John Kessenich32cfd492016-02-02 12:37:46 -07002918 if (firstClass)
2919 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002920
2921 // Handle component-wise +, -, *, and / for all combinations of type.
2922 // The result type of all of them is the same type as the (a) matrix operand.
2923 // The algorithm is to:
2924 // - break the matrix(es) into vectors
2925 // - smear any scalar to a vector
2926 // - do vector operations
2927 // - make a matrix out the vector results
2928 switch (op) {
2929 case spv::OpFAdd:
2930 case spv::OpFSub:
2931 case spv::OpFDiv:
2932 case spv::OpFMul:
2933 {
2934 // one time set up...
2935 bool leftMat = builder.isMatrix(left);
2936 bool rightMat = builder.isMatrix(right);
2937 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2938 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2939 spv::Id scalarType = builder.getScalarTypeId(typeId);
2940 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2941 std::vector<spv::Id> results;
2942 spv::Id smearVec = spv::NoResult;
2943 if (builder.isScalar(left))
2944 smearVec = builder.smearScalar(precision, left, vecType);
2945 else if (builder.isScalar(right))
2946 smearVec = builder.smearScalar(precision, right, vecType);
2947
2948 // do each vector op
2949 for (unsigned int c = 0; c < numCols; ++c) {
2950 std::vector<unsigned int> indexes;
2951 indexes.push_back(c);
2952 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2953 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2954 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2955 builder.setPrecision(results.back(), precision);
2956 }
2957
2958 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002959 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002960 }
2961 default:
2962 assert(0);
2963 return spv::NoResult;
2964 }
2965}
2966
Rex Xu04db3f52015-09-16 11:44:02 +08002967spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06002968{
2969 spv::Op unaryOp = spv::OpNop;
2970 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08002971 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08002972 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002973
2974 switch (op) {
2975 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002976 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002977 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002978 if (builder.isMatrixType(typeId))
2979 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2980 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002981 unaryOp = spv::OpSNegate;
2982 break;
2983
2984 case glslang::EOpLogicalNot:
2985 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002986 unaryOp = spv::OpLogicalNot;
2987 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 case glslang::EOpBitwiseNot:
2989 unaryOp = spv::OpNot;
2990 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002991
John Kessenich140f3df2015-06-26 16:58:36 -06002992 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002997 break;
2998 case glslang::EOpTranspose:
2999 unaryOp = spv::OpTranspose;
3000 break;
3001
3002 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 break;
3014 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003015 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003016 break;
3017 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003018 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003019 break;
3020 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003021 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003022 break;
3023 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003024 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003025 break;
3026
3027 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003031 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 break;
3033 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003034 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 break;
3036 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003037 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003038 break;
3039 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003040 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003041 break;
3042 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003043 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003044 break;
3045
3046 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052
3053 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003054 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003055 break;
3056 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003057 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003058 break;
3059 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003060 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003061 break;
3062 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003063 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003064 break;
3065 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003066 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003067 break;
3068 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003069 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003070 break;
3071
3072 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003073 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 break;
3075 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003076 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003077 break;
3078 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003079 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003080 break;
3081 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003082 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003083 break;
3084 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003086 break;
3087 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003088 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003089 break;
3090
3091 case glslang::EOpIsNan:
3092 unaryOp = spv::OpIsNan;
3093 break;
3094 case glslang::EOpIsInf:
3095 unaryOp = spv::OpIsInf;
3096 break;
3097
Rex Xucbc426e2015-12-15 16:03:10 +08003098 case glslang::EOpFloatBitsToInt:
3099 case glslang::EOpFloatBitsToUint:
3100 case glslang::EOpIntBitsToFloat:
3101 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003102 case glslang::EOpDoubleBitsToInt64:
3103 case glslang::EOpDoubleBitsToUint64:
3104 case glslang::EOpInt64BitsToDouble:
3105 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003106 unaryOp = spv::OpBitcast;
3107 break;
3108
John Kessenich140f3df2015-06-26 16:58:36 -06003109 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003110 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003111 break;
3112 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003114 break;
3115 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003116 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003117 break;
3118 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003119 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 break;
3124 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003125 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003126 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003127 case glslang::EOpPackSnorm4x8:
3128 libCall = spv::GLSLstd450PackSnorm4x8;
3129 break;
3130 case glslang::EOpUnpackSnorm4x8:
3131 libCall = spv::GLSLstd450UnpackSnorm4x8;
3132 break;
3133 case glslang::EOpPackUnorm4x8:
3134 libCall = spv::GLSLstd450PackUnorm4x8;
3135 break;
3136 case glslang::EOpUnpackUnorm4x8:
3137 libCall = spv::GLSLstd450UnpackUnorm4x8;
3138 break;
3139 case glslang::EOpPackDouble2x32:
3140 libCall = spv::GLSLstd450PackDouble2x32;
3141 break;
3142 case glslang::EOpUnpackDouble2x32:
3143 libCall = spv::GLSLstd450UnpackDouble2x32;
3144 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003145
Rex Xu8ff43de2016-04-22 16:51:45 +08003146 case glslang::EOpPackInt2x32:
3147 case glslang::EOpUnpackInt2x32:
3148 case glslang::EOpPackUint2x32:
3149 case glslang::EOpUnpackUint2x32:
3150 spv::MissingFunctionality("shader int64");
3151 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3152 break;
3153
John Kessenich140f3df2015-06-26 16:58:36 -06003154 case glslang::EOpDPdx:
3155 unaryOp = spv::OpDPdx;
3156 break;
3157 case glslang::EOpDPdy:
3158 unaryOp = spv::OpDPdy;
3159 break;
3160 case glslang::EOpFwidth:
3161 unaryOp = spv::OpFwidth;
3162 break;
3163 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003164 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003165 unaryOp = spv::OpDPdxFine;
3166 break;
3167 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003168 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003169 unaryOp = spv::OpDPdyFine;
3170 break;
3171 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003172 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003173 unaryOp = spv::OpFwidthFine;
3174 break;
3175 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003176 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003177 unaryOp = spv::OpDPdxCoarse;
3178 break;
3179 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003180 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003181 unaryOp = spv::OpDPdyCoarse;
3182 break;
3183 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003184 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003185 unaryOp = spv::OpFwidthCoarse;
3186 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003187 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003188 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003189 libCall = spv::GLSLstd450InterpolateAtCentroid;
3190 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 case glslang::EOpAny:
3192 unaryOp = spv::OpAny;
3193 break;
3194 case glslang::EOpAll:
3195 unaryOp = spv::OpAll;
3196 break;
3197
3198 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 if (isFloat)
3200 libCall = spv::GLSLstd450FAbs;
3201 else
3202 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 break;
3204 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003205 if (isFloat)
3206 libCall = spv::GLSLstd450FSign;
3207 else
3208 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003209 break;
3210
John Kessenichfc51d282015-08-19 13:34:18 -06003211 case glslang::EOpAtomicCounterIncrement:
3212 case glslang::EOpAtomicCounterDecrement:
3213 case glslang::EOpAtomicCounter:
3214 {
3215 // Handle all of the atomics in one place, in createAtomicOperation()
3216 std::vector<spv::Id> operands;
3217 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003218 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003219 }
3220
John Kessenichfc51d282015-08-19 13:34:18 -06003221 case glslang::EOpBitFieldReverse:
3222 unaryOp = spv::OpBitReverse;
3223 break;
3224 case glslang::EOpBitCount:
3225 unaryOp = spv::OpBitCount;
3226 break;
3227 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003228 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003229 break;
3230 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003231 if (isUnsigned)
3232 libCall = spv::GLSLstd450FindUMsb;
3233 else
3234 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003235 break;
3236
Rex Xu338b1852016-05-05 20:38:33 +08003237 case glslang::EOpAnyInvocation:
3238 builder.addCapability(spv::CapabilityGroups);
3239 unaryOp = spv::OpGroupAny;
3240 break;
3241 case glslang::EOpAllInvocations:
3242 builder.addCapability(spv::CapabilityGroups);
3243 unaryOp = spv::OpGroupAll;
3244 break;
3245 case glslang::EOpAllInvocationsEqual:
3246 builder.addCapability(spv::CapabilityGroups);
3247 break;
3248
John Kessenich140f3df2015-06-26 16:58:36 -06003249 default:
3250 return 0;
3251 }
3252
3253 spv::Id id;
3254 if (libCall >= 0) {
3255 std::vector<spv::Id> args;
3256 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003257 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003258 } else {
3259 if (op == glslang::EOpAnyInvocation || op == glslang::EOpAllInvocations || op == glslang::EOpAllInvocationsEqual) {
3260 std::vector<spv::Id> operands;
3261 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3262 operands.push_back(operand);
3263
3264 if (op == glslang::EOpAnyInvocation || op == glslang::EOpAllInvocations)
3265 id = builder.createOp(unaryOp, typeId, operands);
3266 else if (op == glslang::EOpAllInvocationsEqual) {
3267 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3268 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3269
3270 id = builder.createBinOp(spv::OpLogicalOr,
3271 typeId,
3272 groupAll,
3273 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3274 }
3275 }
3276 else
3277 id = builder.createUnaryOp(unaryOp, typeId, operand);
3278 }
John Kessenich140f3df2015-06-26 16:58:36 -06003279
John Kessenich32cfd492016-02-02 12:37:46 -07003280 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003281}
3282
John Kessenich7a53f762016-01-20 11:19:27 -07003283// Create a unary operation on a matrix
3284spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3285{
3286 // Handle unary operations vector by vector.
3287 // The result type is the same type as the original type.
3288 // The algorithm is to:
3289 // - break the matrix into vectors
3290 // - apply the operation to each vector
3291 // - make a matrix out the vector results
3292
3293 // get the types sorted out
3294 int numCols = builder.getNumColumns(operand);
3295 int numRows = builder.getNumRows(operand);
3296 spv::Id scalarType = builder.getScalarTypeId(typeId);
3297 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3298 std::vector<spv::Id> results;
3299
3300 // do each vector op
3301 for (int c = 0; c < numCols; ++c) {
3302 std::vector<unsigned int> indexes;
3303 indexes.push_back(c);
3304 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3305 results.push_back(builder.createUnaryOp(op, vecType, vec));
3306 builder.setPrecision(results.back(), precision);
3307 }
3308
3309 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003310 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003311}
3312
John Kessenich140f3df2015-06-26 16:58:36 -06003313spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3314{
3315 spv::Op convOp = spv::OpNop;
3316 spv::Id zero = 0;
3317 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003318 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003319
3320 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3321
3322 switch (op) {
3323 case glslang::EOpConvIntToBool:
3324 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003325 case glslang::EOpConvInt64ToBool:
3326 case glslang::EOpConvUint64ToBool:
3327 zero = (op == glslang::EOpConvInt64ToBool ||
3328 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003329 zero = makeSmearedConstant(zero, vectorSize);
3330 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3331
3332 case glslang::EOpConvFloatToBool:
3333 zero = builder.makeFloatConstant(0.0F);
3334 zero = makeSmearedConstant(zero, vectorSize);
3335 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3336
3337 case glslang::EOpConvDoubleToBool:
3338 zero = builder.makeDoubleConstant(0.0);
3339 zero = makeSmearedConstant(zero, vectorSize);
3340 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3341
3342 case glslang::EOpConvBoolToFloat:
3343 convOp = spv::OpSelect;
3344 zero = builder.makeFloatConstant(0.0);
3345 one = builder.makeFloatConstant(1.0);
3346 break;
3347 case glslang::EOpConvBoolToDouble:
3348 convOp = spv::OpSelect;
3349 zero = builder.makeDoubleConstant(0.0);
3350 one = builder.makeDoubleConstant(1.0);
3351 break;
3352 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003353 case glslang::EOpConvBoolToInt64:
3354 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3355 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003356 convOp = spv::OpSelect;
3357 break;
3358 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003359 case glslang::EOpConvBoolToUint64:
3360 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3361 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003362 convOp = spv::OpSelect;
3363 break;
3364
3365 case glslang::EOpConvIntToFloat:
3366 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003367 case glslang::EOpConvInt64ToFloat:
3368 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003369 convOp = spv::OpConvertSToF;
3370 break;
3371
3372 case glslang::EOpConvUintToFloat:
3373 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003374 case glslang::EOpConvUint64ToFloat:
3375 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003376 convOp = spv::OpConvertUToF;
3377 break;
3378
3379 case glslang::EOpConvDoubleToFloat:
3380 case glslang::EOpConvFloatToDouble:
3381 convOp = spv::OpFConvert;
3382 break;
3383
3384 case glslang::EOpConvFloatToInt:
3385 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003386 case glslang::EOpConvFloatToInt64:
3387 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003388 convOp = spv::OpConvertFToS;
3389 break;
3390
3391 case glslang::EOpConvUintToInt:
3392 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003393 case glslang::EOpConvUint64ToInt64:
3394 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003395 if (builder.isInSpecConstCodeGenMode()) {
3396 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003397 zero = (op == glslang::EOpConvUintToInt64 ||
3398 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003399 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003400 // Use OpIAdd, instead of OpBitcast to do the conversion when
3401 // generating for OpSpecConstantOp instruction.
3402 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3403 }
3404 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003405 convOp = spv::OpBitcast;
3406 break;
3407
3408 case glslang::EOpConvFloatToUint:
3409 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003410 case glslang::EOpConvFloatToUint64:
3411 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003412 convOp = spv::OpConvertFToU;
3413 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003414
3415 case glslang::EOpConvIntToInt64:
3416 case glslang::EOpConvInt64ToInt:
3417 convOp = spv::OpSConvert;
3418 break;
3419
3420 case glslang::EOpConvUintToUint64:
3421 case glslang::EOpConvUint64ToUint:
3422 convOp = spv::OpUConvert;
3423 break;
3424
3425 case glslang::EOpConvIntToUint64:
3426 case glslang::EOpConvInt64ToUint:
3427 case glslang::EOpConvUint64ToInt:
3428 case glslang::EOpConvUintToInt64:
3429 // OpSConvert/OpUConvert + OpBitCast
3430 switch (op) {
3431 case glslang::EOpConvIntToUint64:
3432 convOp = spv::OpSConvert;
3433 type = builder.makeIntType(64);
3434 break;
3435 case glslang::EOpConvInt64ToUint:
3436 convOp = spv::OpSConvert;
3437 type = builder.makeIntType(32);
3438 break;
3439 case glslang::EOpConvUint64ToInt:
3440 convOp = spv::OpUConvert;
3441 type = builder.makeUintType(32);
3442 break;
3443 case glslang::EOpConvUintToInt64:
3444 convOp = spv::OpUConvert;
3445 type = builder.makeUintType(64);
3446 break;
3447 default:
3448 assert(0);
3449 break;
3450 }
3451
3452 if (vectorSize > 0)
3453 type = builder.makeVectorType(type, vectorSize);
3454
3455 operand = builder.createUnaryOp(convOp, type, operand);
3456
3457 if (builder.isInSpecConstCodeGenMode()) {
3458 // Build zero scalar or vector for OpIAdd.
3459 zero = (op == glslang::EOpConvIntToUint64 ||
3460 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3461 zero = makeSmearedConstant(zero, vectorSize);
3462 // Use OpIAdd, instead of OpBitcast to do the conversion when
3463 // generating for OpSpecConstantOp instruction.
3464 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3465 }
3466 // For normal run-time conversion instruction, use OpBitcast.
3467 convOp = spv::OpBitcast;
3468 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 default:
3470 break;
3471 }
3472
3473 spv::Id result = 0;
3474 if (convOp == spv::OpNop)
3475 return result;
3476
3477 if (convOp == spv::OpSelect) {
3478 zero = makeSmearedConstant(zero, vectorSize);
3479 one = makeSmearedConstant(one, vectorSize);
3480 result = builder.createTriOp(convOp, destType, operand, one, zero);
3481 } else
3482 result = builder.createUnaryOp(convOp, destType, operand);
3483
John Kessenich32cfd492016-02-02 12:37:46 -07003484 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003485}
3486
3487spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3488{
3489 if (vectorSize == 0)
3490 return constant;
3491
3492 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3493 std::vector<spv::Id> components;
3494 for (int c = 0; c < vectorSize; ++c)
3495 components.push_back(constant);
3496 return builder.makeCompositeConstant(vectorTypeId, components);
3497}
3498
John Kessenich426394d2015-07-23 10:22:48 -06003499// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003500spv::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 -06003501{
3502 spv::Op opCode = spv::OpNop;
3503
3504 switch (op) {
3505 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003506 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003507 opCode = spv::OpAtomicIAdd;
3508 break;
3509 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003510 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003511 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003512 break;
3513 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003514 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003515 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003516 break;
3517 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003518 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003519 opCode = spv::OpAtomicAnd;
3520 break;
3521 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003522 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003523 opCode = spv::OpAtomicOr;
3524 break;
3525 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003526 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003527 opCode = spv::OpAtomicXor;
3528 break;
3529 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003530 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003531 opCode = spv::OpAtomicExchange;
3532 break;
3533 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003534 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003535 opCode = spv::OpAtomicCompareExchange;
3536 break;
3537 case glslang::EOpAtomicCounterIncrement:
3538 opCode = spv::OpAtomicIIncrement;
3539 break;
3540 case glslang::EOpAtomicCounterDecrement:
3541 opCode = spv::OpAtomicIDecrement;
3542 break;
3543 case glslang::EOpAtomicCounter:
3544 opCode = spv::OpAtomicLoad;
3545 break;
3546 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003547 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003548 break;
3549 }
3550
3551 // Sort out the operands
3552 // - mapping from glslang -> SPV
3553 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003554 // - compare-exchange swaps the value and comparator
3555 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003556 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3557 auto opIt = operands.begin(); // walk the glslang operands
3558 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003559 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3560 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3561 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003562 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3563 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003564 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003565 spvAtomicOperands.push_back(*(opIt + 1));
3566 spvAtomicOperands.push_back(*opIt);
3567 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003568 }
John Kessenich426394d2015-07-23 10:22:48 -06003569
John Kessenich3e60a6f2015-09-14 22:45:16 -06003570 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003571 for (; opIt != operands.end(); ++opIt)
3572 spvAtomicOperands.push_back(*opIt);
3573
3574 return builder.createOp(opCode, typeId, spvAtomicOperands);
3575}
3576
John Kessenich5e4b1242015-08-06 22:53:06 -06003577spv::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 -06003578{
Rex Xu8ff43de2016-04-22 16:51:45 +08003579 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003580 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3581
John Kessenich140f3df2015-06-26 16:58:36 -06003582 spv::Op opCode = spv::OpNop;
3583 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003584 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003585 spv::Id typeId0 = 0;
3586 if (consumedOperands > 0)
3587 typeId0 = builder.getTypeId(operands[0]);
3588 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003589
3590 switch (op) {
3591 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003592 if (isFloat)
3593 libCall = spv::GLSLstd450FMin;
3594 else if (isUnsigned)
3595 libCall = spv::GLSLstd450UMin;
3596 else
3597 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003598 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003599 break;
3600 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003601 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 if (isFloat)
3605 libCall = spv::GLSLstd450FMax;
3606 else if (isUnsigned)
3607 libCall = spv::GLSLstd450UMax;
3608 else
3609 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003610 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003611 break;
3612 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003613 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 break;
3615 case glslang::EOpDot:
3616 opCode = spv::OpDot;
3617 break;
3618 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003619 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003620 break;
3621
3622 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003623 if (isFloat)
3624 libCall = spv::GLSLstd450FClamp;
3625 else if (isUnsigned)
3626 libCall = spv::GLSLstd450UClamp;
3627 else
3628 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003629 builder.promoteScalar(precision, operands.front(), operands[1]);
3630 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003631 break;
3632 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003633 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3634 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003635 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003636 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003637 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003638 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003639 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003640 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003641 break;
3642 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003643 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003644 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003645 break;
3646 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003647 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003648 builder.promoteScalar(precision, operands[0], operands[2]);
3649 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651
3652 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003653 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003654 break;
3655 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003656 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003657 break;
3658 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003659 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003660 break;
3661 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003662 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003663 break;
3664 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003665 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003666 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003667 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003668 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003669 libCall = spv::GLSLstd450InterpolateAtSample;
3670 break;
3671 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003672 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003673 libCall = spv::GLSLstd450InterpolateAtOffset;
3674 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003675 case glslang::EOpAddCarry:
3676 opCode = spv::OpIAddCarry;
3677 typeId = builder.makeStructResultType(typeId0, typeId0);
3678 consumedOperands = 2;
3679 break;
3680 case glslang::EOpSubBorrow:
3681 opCode = spv::OpISubBorrow;
3682 typeId = builder.makeStructResultType(typeId0, typeId0);
3683 consumedOperands = 2;
3684 break;
3685 case glslang::EOpUMulExtended:
3686 opCode = spv::OpUMulExtended;
3687 typeId = builder.makeStructResultType(typeId0, typeId0);
3688 consumedOperands = 2;
3689 break;
3690 case glslang::EOpIMulExtended:
3691 opCode = spv::OpSMulExtended;
3692 typeId = builder.makeStructResultType(typeId0, typeId0);
3693 consumedOperands = 2;
3694 break;
3695 case glslang::EOpBitfieldExtract:
3696 if (isUnsigned)
3697 opCode = spv::OpBitFieldUExtract;
3698 else
3699 opCode = spv::OpBitFieldSExtract;
3700 break;
3701 case glslang::EOpBitfieldInsert:
3702 opCode = spv::OpBitFieldInsert;
3703 break;
3704
3705 case glslang::EOpFma:
3706 libCall = spv::GLSLstd450Fma;
3707 break;
3708 case glslang::EOpFrexp:
3709 libCall = spv::GLSLstd450FrexpStruct;
3710 if (builder.getNumComponents(operands[0]) == 1)
3711 frexpIntType = builder.makeIntegerType(32, true);
3712 else
3713 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3714 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3715 consumedOperands = 1;
3716 break;
3717 case glslang::EOpLdexp:
3718 libCall = spv::GLSLstd450Ldexp;
3719 break;
3720
John Kessenich140f3df2015-06-26 16:58:36 -06003721 default:
3722 return 0;
3723 }
3724
3725 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003726 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003727 // Use an extended instruction from the standard library.
3728 // Construct the call arguments, without modifying the original operands vector.
3729 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3730 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003731 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003732 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003733 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003734 case 0:
3735 // should all be handled by visitAggregate and createNoArgOperation
3736 assert(0);
3737 return 0;
3738 case 1:
3739 // should all be handled by createUnaryOperation
3740 assert(0);
3741 return 0;
3742 case 2:
3743 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3744 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003746 // anything 3 or over doesn't have l-value operands, so all should be consumed
3747 assert(consumedOperands == operands.size());
3748 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750 }
3751 }
3752
John Kessenich55e7d112015-11-15 21:33:39 -07003753 // Decode the return types that were structures
3754 switch (op) {
3755 case glslang::EOpAddCarry:
3756 case glslang::EOpSubBorrow:
3757 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3758 id = builder.createCompositeExtract(id, typeId0, 0);
3759 break;
3760 case glslang::EOpUMulExtended:
3761 case glslang::EOpIMulExtended:
3762 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3763 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3764 break;
3765 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003766 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003767 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3768 id = builder.createCompositeExtract(id, typeId0, 0);
3769 break;
3770 default:
3771 break;
3772 }
3773
John Kessenich32cfd492016-02-02 12:37:46 -07003774 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003775}
3776
3777// Intrinsics with no arguments, no return value, and no precision.
3778spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3779{
3780 // TODO: get the barrier operands correct
3781
3782 switch (op) {
3783 case glslang::EOpEmitVertex:
3784 builder.createNoResultOp(spv::OpEmitVertex);
3785 return 0;
3786 case glslang::EOpEndPrimitive:
3787 builder.createNoResultOp(spv::OpEndPrimitive);
3788 return 0;
3789 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003790 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3791 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003792 return 0;
3793 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003794 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003795 return 0;
3796 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003798 return 0;
3799 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003800 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003801 return 0;
3802 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003803 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003804 return 0;
3805 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003806 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003807 return 0;
3808 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003809 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003810 return 0;
3811 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003812 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003813 return 0;
3814 }
3815}
3816
3817spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3818{
John Kessenich2f273362015-07-18 22:34:27 -06003819 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003820 spv::Id id;
3821 if (symbolValues.end() != iter) {
3822 id = iter->second;
3823 return id;
3824 }
3825
3826 // it was not found, create it
3827 id = createSpvVariable(symbol);
3828 symbolValues[symbol->getId()] = id;
3829
3830 if (! symbol->getType().isStruct()) {
3831 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003832 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003833 if (symbol->getType().getQualifier().hasSpecConstantId())
3834 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 if (symbol->getQualifier().hasLocation())
3836 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3837 if (symbol->getQualifier().hasIndex())
3838 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3839 if (symbol->getQualifier().hasComponent())
3840 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3841 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003842 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003843 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003845 if (symbol->getQualifier().hasXfbBuffer())
3846 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3847 if (symbol->getQualifier().hasXfbOffset())
3848 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3849 }
3850 }
3851
John Kesseniche0b6cad2015-12-24 10:30:13 -07003852 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003853 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003854 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003856 }
John Kessenich140f3df2015-06-26 16:58:36 -06003857 if (symbol->getQualifier().hasSet())
3858 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003859 else if (IsDescriptorResource(symbol->getType())) {
3860 // default to 0
3861 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3862 }
John Kessenich140f3df2015-06-26 16:58:36 -06003863 if (symbol->getQualifier().hasBinding())
3864 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003865 if (symbol->getQualifier().hasAttachment())
3866 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003867 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003868 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003869 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003870 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003871 if (symbol->getQualifier().hasXfbBuffer())
3872 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3873 }
3874
Rex Xu1da878f2016-02-21 20:59:01 +08003875 if (symbol->getType().isImage()) {
3876 std::vector<spv::Decoration> memory;
3877 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3878 for (unsigned int i = 0; i < memory.size(); ++i)
3879 addDecoration(id, memory[i]);
3880 }
3881
John Kessenich140f3df2015-06-26 16:58:36 -06003882 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003883 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003884 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003885 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003886
John Kessenich140f3df2015-06-26 16:58:36 -06003887 return id;
3888}
3889
John Kessenich55e7d112015-11-15 21:33:39 -07003890// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003891void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3892{
3893 if (dec != spv::BadValue)
3894 builder.addDecoration(id, dec);
3895}
3896
John Kessenich55e7d112015-11-15 21:33:39 -07003897// If 'dec' is valid, add a one-operand decoration to an object
3898void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3899{
3900 if (dec != spv::BadValue)
3901 builder.addDecoration(id, dec, value);
3902}
3903
3904// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003905void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3906{
3907 if (dec != spv::BadValue)
3908 builder.addMemberDecoration(id, (unsigned)member, dec);
3909}
3910
John Kessenich92187592016-02-01 13:45:25 -07003911// If 'dec' is valid, add a one-operand decoration to a struct member
3912void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3913{
3914 if (dec != spv::BadValue)
3915 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3916}
3917
John Kessenich55e7d112015-11-15 21:33:39 -07003918// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003919// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003920//
3921// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3922//
3923// Recursively walk the nodes. The nodes form a tree whose leaves are
3924// regular constants, which themselves are trees that createSpvConstant()
3925// recursively walks. So, this function walks the "top" of the tree:
3926// - emit specialization constant-building instructions for specConstant
3927// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003928spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003929{
John Kessenich7cc0e282016-03-20 00:46:02 -06003930 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003931
qining4f4bb812016-04-03 23:55:17 -04003932 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003933 if (! node.getQualifier().specConstant) {
3934 // hand off to the non-spec-constant path
3935 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3936 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003937 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003938 nextConst, false);
3939 }
3940
3941 // We now know we have a specialization constant to build
3942
qining4f4bb812016-04-03 23:55:17 -04003943 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3944 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3945 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3946 std::vector<spv::Id> dimConstId;
3947 for (int dim = 0; dim < 3; ++dim) {
3948 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3949 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3950 if (specConst)
3951 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3952 }
3953 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3954 }
3955
3956 // An AST node labelled as specialization constant should be a symbol node.
3957 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3958 if (auto* sn = node.getAsSymbolNode()) {
3959 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04003960 // Traverse the constant constructor sub tree like generating normal run-time instructions.
3961 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
3962 // will set the builder into spec constant op instruction generating mode.
3963 sub_tree->traverse(this);
3964 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04003965 } else if (auto* const_union_array = &sn->getConstArray()){
3966 int nextConst = 0;
3967 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003968 }
3969 }
qining4f4bb812016-04-03 23:55:17 -04003970
3971 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3972 // constant sub tree as initializer.
3973 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3974 exit(1);
3975 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003976}
3977
John Kessenich140f3df2015-06-26 16:58:36 -06003978// Use 'consts' as the flattened glslang source of scalar constants to recursively
3979// build the aggregate SPIR-V constant.
3980//
3981// If there are not enough elements present in 'consts', 0 will be substituted;
3982// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3983//
qining08408382016-03-21 09:51:37 -04003984spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003985{
3986 // vector of constants for SPIR-V
3987 std::vector<spv::Id> spvConsts;
3988
3989 // Type is used for struct and array constants
3990 spv::Id typeId = convertGlslangToSpvType(glslangType);
3991
3992 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003993 glslang::TType elementType(glslangType, 0);
3994 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003995 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003996 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003997 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003998 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003999 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004000 } else if (glslangType.getStruct()) {
4001 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4002 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004003 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004004 } else if (glslangType.isVector()) {
4005 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4006 bool zero = nextConst >= consts.size();
4007 switch (glslangType.getBasicType()) {
4008 case glslang::EbtInt:
4009 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4010 break;
4011 case glslang::EbtUint:
4012 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4013 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004014 case glslang::EbtInt64:
4015 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4016 break;
4017 case glslang::EbtUint64:
4018 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4019 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004020 case glslang::EbtFloat:
4021 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4022 break;
4023 case glslang::EbtDouble:
4024 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4025 break;
4026 case glslang::EbtBool:
4027 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4028 break;
4029 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004030 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004031 break;
4032 }
4033 ++nextConst;
4034 }
4035 } else {
4036 // we have a non-aggregate (scalar) constant
4037 bool zero = nextConst >= consts.size();
4038 spv::Id scalar = 0;
4039 switch (glslangType.getBasicType()) {
4040 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004041 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004042 break;
4043 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004044 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004045 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004046 case glslang::EbtInt64:
4047 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4048 break;
4049 case glslang::EbtUint64:
4050 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4051 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004052 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004053 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004056 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004059 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004062 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 }
4065 ++nextConst;
4066 return scalar;
4067 }
4068
4069 return builder.makeCompositeConstant(typeId, spvConsts);
4070}
4071
John Kessenich7c1aa102015-10-15 13:29:11 -06004072// Return true if the node is a constant or symbol whose reading has no
4073// non-trivial observable cost or effect.
4074bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4075{
4076 // don't know what this is
4077 if (node == nullptr)
4078 return false;
4079
4080 // a constant is safe
4081 if (node->getAsConstantUnion() != nullptr)
4082 return true;
4083
4084 // not a symbol means non-trivial
4085 if (node->getAsSymbolNode() == nullptr)
4086 return false;
4087
4088 // a symbol, depends on what's being read
4089 switch (node->getType().getQualifier().storage) {
4090 case glslang::EvqTemporary:
4091 case glslang::EvqGlobal:
4092 case glslang::EvqIn:
4093 case glslang::EvqInOut:
4094 case glslang::EvqConst:
4095 case glslang::EvqConstReadOnly:
4096 case glslang::EvqUniform:
4097 return true;
4098 default:
4099 return false;
4100 }
4101}
4102
4103// A node is trivial if it is a single operation with no side effects.
4104// Error on the side of saying non-trivial.
4105// Return true if trivial.
4106bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4107{
4108 if (node == nullptr)
4109 return false;
4110
4111 // symbols and constants are trivial
4112 if (isTrivialLeaf(node))
4113 return true;
4114
4115 // otherwise, it needs to be a simple operation or one or two leaf nodes
4116
4117 // not a simple operation
4118 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4119 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4120 if (binaryNode == nullptr && unaryNode == nullptr)
4121 return false;
4122
4123 // not on leaf nodes
4124 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4125 return false;
4126
4127 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4128 return false;
4129 }
4130
4131 switch (node->getAsOperator()->getOp()) {
4132 case glslang::EOpLogicalNot:
4133 case glslang::EOpConvIntToBool:
4134 case glslang::EOpConvUintToBool:
4135 case glslang::EOpConvFloatToBool:
4136 case glslang::EOpConvDoubleToBool:
4137 case glslang::EOpEqual:
4138 case glslang::EOpNotEqual:
4139 case glslang::EOpLessThan:
4140 case glslang::EOpGreaterThan:
4141 case glslang::EOpLessThanEqual:
4142 case glslang::EOpGreaterThanEqual:
4143 case glslang::EOpIndexDirect:
4144 case glslang::EOpIndexDirectStruct:
4145 case glslang::EOpLogicalXor:
4146 case glslang::EOpAny:
4147 case glslang::EOpAll:
4148 return true;
4149 default:
4150 return false;
4151 }
4152}
4153
4154// Emit short-circuiting code, where 'right' is never evaluated unless
4155// the left side is true (for &&) or false (for ||).
4156spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4157{
4158 spv::Id boolTypeId = builder.makeBoolType();
4159
4160 // emit left operand
4161 builder.clearAccessChain();
4162 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004163 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004164
4165 // Operands to accumulate OpPhi operands
4166 std::vector<spv::Id> phiOperands;
4167 // accumulate left operand's phi information
4168 phiOperands.push_back(leftId);
4169 phiOperands.push_back(builder.getBuildPoint()->getId());
4170
4171 // Make the two kinds of operation symmetric with a "!"
4172 // || => emit "if (! left) result = right"
4173 // && => emit "if ( left) result = right"
4174 //
4175 // TODO: this runtime "not" for || could be avoided by adding functionality
4176 // to 'builder' to have an "else" without an "then"
4177 if (op == glslang::EOpLogicalOr)
4178 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4179
4180 // make an "if" based on the left value
4181 spv::Builder::If ifBuilder(leftId, builder);
4182
4183 // emit right operand as the "then" part of the "if"
4184 builder.clearAccessChain();
4185 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004186 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004187
4188 // accumulate left operand's phi information
4189 phiOperands.push_back(rightId);
4190 phiOperands.push_back(builder.getBuildPoint()->getId());
4191
4192 // finish the "if"
4193 ifBuilder.makeEndIf();
4194
4195 // phi together the two results
4196 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4197}
4198
John Kessenich140f3df2015-06-26 16:58:36 -06004199}; // end anonymous namespace
4200
4201namespace glslang {
4202
John Kessenich68d78fd2015-07-12 19:28:10 -06004203void GetSpirvVersion(std::string& version)
4204{
John Kessenich9e55f632015-07-15 10:03:39 -06004205 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004206 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004207 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004208 version = buf;
4209}
4210
John Kessenich140f3df2015-06-26 16:58:36 -06004211// Write SPIR-V out to a binary file
4212void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4213{
4214 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004215 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004216 for (int i = 0; i < (int)spirv.size(); ++i) {
4217 unsigned int word = spirv[i];
4218 out.write((const char*)&word, 4);
4219 }
4220 out.close();
4221}
4222
4223//
4224// Set up the glslang traversal
4225//
4226void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4227{
4228 TIntermNode* root = intermediate.getTreeRoot();
4229
4230 if (root == 0)
4231 return;
4232
4233 glslang::GetThreadPoolAllocator().push();
4234
4235 TGlslangToSpvTraverser it(&intermediate);
4236
4237 root->traverse(&it);
4238
4239 it.dumpSpv(spirv);
4240
4241 glslang::GetThreadPoolAllocator().pop();
4242}
4243
4244}; // end namespace glslang