blob: 9d4dc59038ac5cd849913ec0b72dd308add1841d [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
1072 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1073 builder.makeFloatConstant(1.0F) :
1074 builder.makeIntConstant(1);
1075 glslang::TOperator op;
1076 if (node->getOp() == glslang::EOpPreIncrement ||
1077 node->getOp() == glslang::EOpPostIncrement)
1078 op = glslang::EOpAdd;
1079 else
1080 op = glslang::EOpSub;
1081
1082 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1083 convertGlslangToSpvType(node->getType()), operand, one,
1084 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001085 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001086
1087 // The result of operation is always stored, but conditionally the
1088 // consumed result. The consumed result is always an r-value.
1089 builder.accessChainStore(result);
1090 builder.clearAccessChain();
1091 if (node->getOp() == glslang::EOpPreIncrement ||
1092 node->getOp() == glslang::EOpPreDecrement)
1093 builder.setAccessChainRValue(result);
1094 else
1095 builder.setAccessChainRValue(operand);
1096 }
1097
1098 return false;
1099
1100 case glslang::EOpEmitStreamVertex:
1101 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1102 return false;
1103 case glslang::EOpEndStreamPrimitive:
1104 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1105 return false;
1106
1107 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001108 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001109 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001110 }
John Kessenich140f3df2015-06-26 16:58:36 -06001111}
1112
1113bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1114{
qining27e04a02016-04-14 16:40:20 -04001115 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1116 if (node->getType().getQualifier().isSpecConstant())
1117 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1118
John Kessenichfc51d282015-08-19 13:34:18 -06001119 spv::Id result = spv::NoResult;
1120
1121 // try texturing
1122 result = createImageTextureFunctionCall(node);
1123 if (result != spv::NoResult) {
1124 builder.clearAccessChain();
1125 builder.setAccessChainRValue(result);
1126
1127 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001128 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001129 // "imageStore" is a special case, which has no result
1130 return false;
1131 }
John Kessenichfc51d282015-08-19 13:34:18 -06001132
John Kessenich140f3df2015-06-26 16:58:36 -06001133 glslang::TOperator binOp = glslang::EOpNull;
1134 bool reduceComparison = true;
1135 bool isMatrix = false;
1136 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001137 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001138
1139 assert(node->getOp());
1140
1141 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1142
1143 switch (node->getOp()) {
1144 case glslang::EOpSequence:
1145 {
1146 if (preVisit)
1147 ++sequenceDepth;
1148 else
1149 --sequenceDepth;
1150
1151 if (sequenceDepth == 1) {
1152 // If this is the parent node of all the functions, we want to see them
1153 // early, so all call points have actual SPIR-V functions to reference.
1154 // In all cases, still let the traverser visit the children for us.
1155 makeFunctions(node->getAsAggregate()->getSequence());
1156
1157 // Also, we want all globals initializers to go into the entry of main(), before
1158 // anything else gets there, so visit out of order, doing them all now.
1159 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1160
1161 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1162 // so do them manually.
1163 visitFunctions(node->getAsAggregate()->getSequence());
1164
1165 return false;
1166 }
1167
1168 return true;
1169 }
1170 case glslang::EOpLinkerObjects:
1171 {
1172 if (visit == glslang::EvPreVisit)
1173 linkageOnly = true;
1174 else
1175 linkageOnly = false;
1176
1177 return true;
1178 }
1179 case glslang::EOpComma:
1180 {
1181 // processing from left to right naturally leaves the right-most
1182 // lying around in the access chain
1183 glslang::TIntermSequence& glslangOperands = node->getSequence();
1184 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1185 glslangOperands[i]->traverse(this);
1186
1187 return false;
1188 }
1189 case glslang::EOpFunction:
1190 if (visit == glslang::EvPreVisit) {
1191 if (isShaderEntrypoint(node)) {
1192 inMain = true;
1193 builder.setBuildPoint(shaderEntry->getLastBlock());
1194 } else {
1195 handleFunctionEntry(node);
1196 }
1197 } else {
1198 if (inMain)
1199 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001200 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001201 inMain = false;
1202 }
1203
1204 return true;
1205 case glslang::EOpParameters:
1206 // Parameters will have been consumed by EOpFunction processing, but not
1207 // the body, so we still visited the function node's children, making this
1208 // child redundant.
1209 return false;
1210 case glslang::EOpFunctionCall:
1211 {
1212 if (node->isUserDefined())
1213 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001214 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1215 if (result) {
1216 builder.clearAccessChain();
1217 builder.setAccessChainRValue(result);
1218 } else
1219 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001220
1221 return false;
1222 }
1223 case glslang::EOpConstructMat2x2:
1224 case glslang::EOpConstructMat2x3:
1225 case glslang::EOpConstructMat2x4:
1226 case glslang::EOpConstructMat3x2:
1227 case glslang::EOpConstructMat3x3:
1228 case glslang::EOpConstructMat3x4:
1229 case glslang::EOpConstructMat4x2:
1230 case glslang::EOpConstructMat4x3:
1231 case glslang::EOpConstructMat4x4:
1232 case glslang::EOpConstructDMat2x2:
1233 case glslang::EOpConstructDMat2x3:
1234 case glslang::EOpConstructDMat2x4:
1235 case glslang::EOpConstructDMat3x2:
1236 case glslang::EOpConstructDMat3x3:
1237 case glslang::EOpConstructDMat3x4:
1238 case glslang::EOpConstructDMat4x2:
1239 case glslang::EOpConstructDMat4x3:
1240 case glslang::EOpConstructDMat4x4:
1241 isMatrix = true;
1242 // fall through
1243 case glslang::EOpConstructFloat:
1244 case glslang::EOpConstructVec2:
1245 case glslang::EOpConstructVec3:
1246 case glslang::EOpConstructVec4:
1247 case glslang::EOpConstructDouble:
1248 case glslang::EOpConstructDVec2:
1249 case glslang::EOpConstructDVec3:
1250 case glslang::EOpConstructDVec4:
1251 case glslang::EOpConstructBool:
1252 case glslang::EOpConstructBVec2:
1253 case glslang::EOpConstructBVec3:
1254 case glslang::EOpConstructBVec4:
1255 case glslang::EOpConstructInt:
1256 case glslang::EOpConstructIVec2:
1257 case glslang::EOpConstructIVec3:
1258 case glslang::EOpConstructIVec4:
1259 case glslang::EOpConstructUint:
1260 case glslang::EOpConstructUVec2:
1261 case glslang::EOpConstructUVec3:
1262 case glslang::EOpConstructUVec4:
1263 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001264 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001265 {
1266 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001267 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001268 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1269 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001270 if (node->getOp() == glslang::EOpConstructTextureSampler)
1271 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1272 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001273 std::vector<spv::Id> constituents;
1274 for (int c = 0; c < (int)arguments.size(); ++c)
1275 constituents.push_back(arguments[c]);
1276 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001277 } else if (isMatrix)
1278 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1279 else
1280 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001281
1282 builder.clearAccessChain();
1283 builder.setAccessChainRValue(constructed);
1284
1285 return false;
1286 }
1287
1288 // These six are component-wise compares with component-wise results.
1289 // Forward on to createBinaryOperation(), requesting a vector result.
1290 case glslang::EOpLessThan:
1291 case glslang::EOpGreaterThan:
1292 case glslang::EOpLessThanEqual:
1293 case glslang::EOpGreaterThanEqual:
1294 case glslang::EOpVectorEqual:
1295 case glslang::EOpVectorNotEqual:
1296 {
1297 // Map the operation to a binary
1298 binOp = node->getOp();
1299 reduceComparison = false;
1300 switch (node->getOp()) {
1301 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1302 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1303 default: binOp = node->getOp(); break;
1304 }
1305
1306 break;
1307 }
1308 case glslang::EOpMul:
1309 // compontent-wise matrix multiply
1310 binOp = glslang::EOpMul;
1311 break;
1312 case glslang::EOpOuterProduct:
1313 // two vectors multiplied to make a matrix
1314 binOp = glslang::EOpOuterProduct;
1315 break;
1316 case glslang::EOpDot:
1317 {
1318 // for scalar dot product, use multiply
1319 glslang::TIntermSequence& glslangOperands = node->getSequence();
1320 if (! glslangOperands[0]->getAsTyped()->isVector())
1321 binOp = glslang::EOpMul;
1322 break;
1323 }
1324 case glslang::EOpMod:
1325 // when an aggregate, this is the floating-point mod built-in function,
1326 // which can be emitted by the one in createBinaryOperation()
1327 binOp = glslang::EOpMod;
1328 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001329 case glslang::EOpEmitVertex:
1330 case glslang::EOpEndPrimitive:
1331 case glslang::EOpBarrier:
1332 case glslang::EOpMemoryBarrier:
1333 case glslang::EOpMemoryBarrierAtomicCounter:
1334 case glslang::EOpMemoryBarrierBuffer:
1335 case glslang::EOpMemoryBarrierImage:
1336 case glslang::EOpMemoryBarrierShared:
1337 case glslang::EOpGroupMemoryBarrier:
1338 noReturnValue = true;
1339 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1340 break;
1341
John Kessenich426394d2015-07-23 10:22:48 -06001342 case glslang::EOpAtomicAdd:
1343 case glslang::EOpAtomicMin:
1344 case glslang::EOpAtomicMax:
1345 case glslang::EOpAtomicAnd:
1346 case glslang::EOpAtomicOr:
1347 case glslang::EOpAtomicXor:
1348 case glslang::EOpAtomicExchange:
1349 case glslang::EOpAtomicCompSwap:
1350 atomic = true;
1351 break;
1352
John Kessenich140f3df2015-06-26 16:58:36 -06001353 default:
1354 break;
1355 }
1356
1357 //
1358 // See if it maps to a regular operation.
1359 //
John Kessenich140f3df2015-06-26 16:58:36 -06001360 if (binOp != glslang::EOpNull) {
1361 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1362 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1363 assert(left && right);
1364
1365 builder.clearAccessChain();
1366 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001367 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001368
1369 builder.clearAccessChain();
1370 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001371 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001372
1373 result = createBinaryOperation(binOp, precision,
1374 convertGlslangToSpvType(node->getType()), leftId, rightId,
1375 left->getType().getBasicType(), reduceComparison);
1376
1377 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001378 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001379 builder.clearAccessChain();
1380 builder.setAccessChainRValue(result);
1381
1382 return false;
1383 }
1384
John Kessenich426394d2015-07-23 10:22:48 -06001385 //
1386 // Create the list of operands.
1387 //
John Kessenich140f3df2015-06-26 16:58:36 -06001388 glslang::TIntermSequence& glslangOperands = node->getSequence();
1389 std::vector<spv::Id> operands;
1390 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1391 builder.clearAccessChain();
1392 glslangOperands[arg]->traverse(this);
1393
1394 // special case l-value operands; there are just a few
1395 bool lvalue = false;
1396 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001397 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001398 case glslang::EOpModf:
1399 if (arg == 1)
1400 lvalue = true;
1401 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001402 case glslang::EOpInterpolateAtSample:
1403 case glslang::EOpInterpolateAtOffset:
1404 if (arg == 0)
1405 lvalue = true;
1406 break;
Rex Xud4782c12015-09-06 16:30:11 +08001407 case glslang::EOpAtomicAdd:
1408 case glslang::EOpAtomicMin:
1409 case glslang::EOpAtomicMax:
1410 case glslang::EOpAtomicAnd:
1411 case glslang::EOpAtomicOr:
1412 case glslang::EOpAtomicXor:
1413 case glslang::EOpAtomicExchange:
1414 case glslang::EOpAtomicCompSwap:
1415 if (arg == 0)
1416 lvalue = true;
1417 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001418 case glslang::EOpAddCarry:
1419 case glslang::EOpSubBorrow:
1420 if (arg == 2)
1421 lvalue = true;
1422 break;
1423 case glslang::EOpUMulExtended:
1424 case glslang::EOpIMulExtended:
1425 if (arg >= 2)
1426 lvalue = true;
1427 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001428 default:
1429 break;
1430 }
1431 if (lvalue)
1432 operands.push_back(builder.accessChainGetLValue());
1433 else
John Kessenich32cfd492016-02-02 12:37:46 -07001434 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001435 }
John Kessenich426394d2015-07-23 10:22:48 -06001436
1437 if (atomic) {
1438 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001439 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001440 } else {
1441 // Pass through to generic operations.
1442 switch (glslangOperands.size()) {
1443 case 0:
1444 result = createNoArgOperation(node->getOp());
1445 break;
1446 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001447 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001448 break;
1449 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001450 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001451 break;
1452 }
John Kessenich140f3df2015-06-26 16:58:36 -06001453 }
1454
1455 if (noReturnValue)
1456 return false;
1457
1458 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001459 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001460 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001461 } else {
1462 builder.clearAccessChain();
1463 builder.setAccessChainRValue(result);
1464 return false;
1465 }
1466}
1467
1468bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1469{
1470 // This path handles both if-then-else and ?:
1471 // The if-then-else has a node type of void, while
1472 // ?: has a non-void node type
1473 spv::Id result = 0;
1474 if (node->getBasicType() != glslang::EbtVoid) {
1475 // don't handle this as just on-the-fly temporaries, because there will be two names
1476 // and better to leave SSA to later passes
1477 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1478 }
1479
1480 // emit the condition before doing anything with selection
1481 node->getCondition()->traverse(this);
1482
1483 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001484 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001485
1486 if (node->getTrueBlock()) {
1487 // emit the "then" statement
1488 node->getTrueBlock()->traverse(this);
1489 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001490 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001491 }
1492
1493 if (node->getFalseBlock()) {
1494 ifBuilder.makeBeginElse();
1495 // emit the "else" statement
1496 node->getFalseBlock()->traverse(this);
1497 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001498 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001499 }
1500
1501 ifBuilder.makeEndIf();
1502
1503 if (result) {
1504 // GLSL only has r-values as the result of a :?, but
1505 // if we have an l-value, that can be more efficient if it will
1506 // become the base of a complex r-value expression, because the
1507 // next layer copies r-values into memory to use the access-chain mechanism
1508 builder.clearAccessChain();
1509 builder.setAccessChainLValue(result);
1510 }
1511
1512 return false;
1513}
1514
1515bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1516{
1517 // emit and get the condition before doing anything with switch
1518 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001519 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001520
1521 // browse the children to sort out code segments
1522 int defaultSegment = -1;
1523 std::vector<TIntermNode*> codeSegments;
1524 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1525 std::vector<int> caseValues;
1526 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1527 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1528 TIntermNode* child = *c;
1529 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001530 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001531 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001532 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001533 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1534 } else
1535 codeSegments.push_back(child);
1536 }
1537
1538 // handle the case where the last code segment is missing, due to no code
1539 // statements between the last case and the end of the switch statement
1540 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1541 (int)codeSegments.size() == defaultSegment)
1542 codeSegments.push_back(nullptr);
1543
1544 // make the switch statement
1545 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001546 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001547
1548 // emit all the code in the segments
1549 breakForLoop.push(false);
1550 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1551 builder.nextSwitchSegment(segmentBlocks, s);
1552 if (codeSegments[s])
1553 codeSegments[s]->traverse(this);
1554 else
1555 builder.addSwitchBreak();
1556 }
1557 breakForLoop.pop();
1558
1559 builder.endSwitch(segmentBlocks);
1560
1561 return false;
1562}
1563
1564void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1565{
1566 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001567 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001568
1569 builder.clearAccessChain();
1570 builder.setAccessChainRValue(constant);
1571}
1572
1573bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1574{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001575 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001576 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001577 // Spec requires back edges to target header blocks, and every header block
1578 // must dominate its merge block. Make a header block first to ensure these
1579 // conditions are met. By definition, it will contain OpLoopMerge, followed
1580 // by a block-ending branch. But we don't want to put any other body/test
1581 // instructions in it, since the body/test may have arbitrary instructions,
1582 // including merges of its own.
1583 builder.setBuildPoint(&blocks.head);
1584 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001585 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001586 spv::Block& test = builder.makeNewBlock();
1587 builder.createBranch(&test);
1588
1589 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001590 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001591 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001592 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001593 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1594
1595 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001596 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001597 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001598 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001599 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001600 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001601
1602 builder.setBuildPoint(&blocks.continue_target);
1603 if (node->getTerminal())
1604 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001605 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001606 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001607 builder.createBranch(&blocks.body);
1608
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001609 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001610 builder.setBuildPoint(&blocks.body);
1611 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001612 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001613 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001614 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001615
1616 builder.setBuildPoint(&blocks.continue_target);
1617 if (node->getTerminal())
1618 node->getTerminal()->traverse(this);
1619 if (node->getTest()) {
1620 node->getTest()->traverse(this);
1621 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001622 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001623 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001624 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001625 // TODO: unless there was a break/return/discard instruction
1626 // somewhere in the body, this is an infinite loop, so we should
1627 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001628 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001629 }
John Kessenich140f3df2015-06-26 16:58:36 -06001630 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001631 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001632 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001633 return false;
1634}
1635
1636bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1637{
1638 if (node->getExpression())
1639 node->getExpression()->traverse(this);
1640
1641 switch (node->getFlowOp()) {
1642 case glslang::EOpKill:
1643 builder.makeDiscard();
1644 break;
1645 case glslang::EOpBreak:
1646 if (breakForLoop.top())
1647 builder.createLoopExit();
1648 else
1649 builder.addSwitchBreak();
1650 break;
1651 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001652 builder.createLoopContinue();
1653 break;
1654 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001655 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001656 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001657 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001658 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001659
1660 builder.clearAccessChain();
1661 break;
1662
1663 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001664 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001665 break;
1666 }
1667
1668 return false;
1669}
1670
1671spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1672{
1673 // First, steer off constants, which are not SPIR-V variables, but
1674 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001675 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001676 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001677 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001678 }
1679
1680 // Now, handle actual variables
1681 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1682 spv::Id spvType = convertGlslangToSpvType(node->getType());
1683
1684 const char* name = node->getName().c_str();
1685 if (glslang::IsAnonymous(name))
1686 name = "";
1687
1688 return builder.createVariable(storageClass, spvType, name);
1689}
1690
1691// Return type Id of the sampled type.
1692spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1693{
1694 switch (sampler.type) {
1695 case glslang::EbtFloat: return builder.makeFloatType(32);
1696 case glslang::EbtInt: return builder.makeIntType(32);
1697 case glslang::EbtUint: return builder.makeUintType(32);
1698 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001699 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 return builder.makeFloatType(32);
1701 }
1702}
1703
John Kessenich3ac051e2015-12-20 11:29:16 -07001704// Convert from a glslang type to an SPV type, by calling into a
1705// recursive version of this function. This establishes the inherited
1706// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001707spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1708{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001709 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001710}
1711
1712// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001713// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001714spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001715{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001716 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001717
1718 switch (type.getBasicType()) {
1719 case glslang::EbtVoid:
1720 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001721 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001722 break;
1723 case glslang::EbtFloat:
1724 spvType = builder.makeFloatType(32);
1725 break;
1726 case glslang::EbtDouble:
1727 spvType = builder.makeFloatType(64);
1728 break;
1729 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001730 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1731 // a 32-bit int where non-0 means true.
1732 if (explicitLayout != glslang::ElpNone)
1733 spvType = builder.makeUintType(32);
1734 else
1735 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001736 break;
1737 case glslang::EbtInt:
1738 spvType = builder.makeIntType(32);
1739 break;
1740 case glslang::EbtUint:
1741 spvType = builder.makeUintType(32);
1742 break;
John Kessenich426394d2015-07-23 10:22:48 -06001743 case glslang::EbtAtomicUint:
1744 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1745 spvType = builder.makeUintType(32);
1746 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001747 case glslang::EbtSampler:
1748 {
1749 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001750 if (sampler.sampler) {
1751 // pure sampler
1752 spvType = builder.makeSamplerType();
1753 } else {
1754 // an image is present, make its type
1755 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1756 sampler.image ? 2 : 1, TranslateImageFormat(type));
1757 if (sampler.combined) {
1758 // already has both image and sampler, make the combined type
1759 spvType = builder.makeSampledImageType(spvType);
1760 }
John Kessenich55e7d112015-11-15 21:33:39 -07001761 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001762 }
John Kessenich140f3df2015-06-26 16:58:36 -06001763 break;
1764 case glslang::EbtStruct:
1765 case glslang::EbtBlock:
1766 {
1767 // If we've seen this struct type, return it
1768 const glslang::TTypeList* glslangStruct = type.getStruct();
1769 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001770
1771 // Try to share structs for different layouts, but not yet for other
1772 // kinds of qualification (primarily not yet including interpolant qualification).
1773 if (! HasNonLayoutQualifiers(qualifier))
1774 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1775 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001776 break;
1777
1778 // else, we haven't seen it...
1779
1780 // Create a vector of struct types for SPIR-V to consume
1781 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1782 if (type.getBasicType() == glslang::EbtBlock)
1783 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001784 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001785 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1786 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1787 if (glslangType.hiddenMember()) {
1788 ++memberDelta;
1789 if (type.getBasicType() == glslang::EbtBlock)
1790 memberRemapper[glslangStruct][i] = -1;
1791 } else {
1792 if (type.getBasicType() == glslang::EbtBlock)
1793 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001794 // modify just this child's view of the qualifier
1795 glslang::TQualifier subQualifier = glslangType.getQualifier();
1796 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001797
1798 // manually inherit location; it's more complex
1799 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1800 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1801 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001802 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001803
1804 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001805 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001806 }
1807 }
1808
1809 // Make the SPIR-V type
1810 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001811 if (! HasNonLayoutQualifiers(qualifier))
1812 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001813
1814 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001815 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001816 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001817 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1818 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1819 int member = i;
1820 if (type.getBasicType() == glslang::EbtBlock)
1821 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001822
John Kesseniche0b6cad2015-12-24 10:30:13 -07001823 // modify just this child's view of the qualifier
1824 glslang::TQualifier subQualifier = glslangType.getQualifier();
1825 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001826
John Kessenich140f3df2015-06-26 16:58:36 -06001827 // using -1 above to indicate a hidden member
1828 if (member >= 0) {
1829 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001830 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001831 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001832 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1833 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001834
Rex Xu1da878f2016-02-21 20:59:01 +08001835 if (qualifier.storage == glslang::EvqBuffer) {
1836 std::vector<spv::Decoration> memory;
1837 TranslateMemoryDecoration(subQualifier, memory);
1838 for (unsigned int i = 0; i < memory.size(); ++i)
1839 addMemberDecoration(spvType, member, memory[i]);
1840 }
1841
John Kessenich09677482016-02-19 12:21:50 -07001842 // compute location decoration; tricky based on whether inheritance is at play
1843 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1844 // probably move to the linker stage of the front end proper, and just have the
1845 // answer sitting already distributed throughout the individual member locations.
1846 int location = -1; // will only decorate if present or inherited
1847 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1848 location = subQualifier.layoutLocation;
1849 else if (qualifier.hasLocation()) // inheritance
1850 location = qualifier.layoutLocation + locationOffset;
1851 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001852 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001853 if (location >= 0)
1854 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1855
1856 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001857 if (glslangType.getQualifier().hasComponent())
1858 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1859 if (glslangType.getQualifier().hasXfbOffset())
1860 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001861 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001862 // figure out what to do with offset, which is accumulating
1863 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001864 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001865 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001866 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001867 offset = nextOffset;
1868 }
John Kessenich140f3df2015-06-26 16:58:36 -06001869
John Kessenichf85e8062015-12-19 13:57:10 -07001870 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001871 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001872
John Kessenich140f3df2015-06-26 16:58:36 -06001873 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001874 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1875 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001876 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001877 }
1878 }
1879
1880 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001881 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001882 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001883 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001884 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001885 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001886 }
John Kessenich140f3df2015-06-26 16:58:36 -06001887 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001888 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001889 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001890 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001891 if (type.getQualifier().hasXfbBuffer())
1892 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1893 }
1894 }
1895 break;
1896 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001897 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001898 break;
1899 }
1900
1901 if (type.isMatrix())
1902 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1903 else {
1904 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1905 if (type.getVectorSize() > 1)
1906 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1907 }
1908
1909 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001910 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1911
John Kessenichc9a80832015-09-12 12:17:44 -06001912 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001913 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001914 // We need to decorate array strides for types needing explicit layout, except blocks.
1915 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001916 // Use a dummy glslang type for querying internal strides of
1917 // arrays of arrays, but using just a one-dimensional array.
1918 glslang::TType simpleArrayType(type, 0); // deference type of the array
1919 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1920 simpleArrayType.getArraySizes().dereference();
1921
1922 // Will compute the higher-order strides here, rather than making a whole
1923 // pile of types and doing repetitive recursion on their contents.
1924 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1925 }
John Kessenichf8842e52016-01-04 19:22:56 -07001926
1927 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001928 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001929 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001930 if (stride > 0)
1931 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001932 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001933 }
1934 } else {
1935 // single-dimensional array, and don't yet have stride
1936
John Kessenichf8842e52016-01-04 19:22:56 -07001937 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001938 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1939 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001940 }
John Kessenich31ed4832015-09-09 17:51:38 -06001941
John Kessenichc9a80832015-09-12 12:17:44 -06001942 // Do the outer dimension, which might not be known for a runtime-sized array
1943 if (type.isRuntimeSizedArray()) {
1944 spvType = builder.makeRuntimeArray(spvType);
1945 } else {
1946 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001947 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001948 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001949 if (stride > 0)
1950 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001951 }
1952
1953 return spvType;
1954}
1955
John Kessenich6c292d32016-02-15 20:58:50 -07001956// Turn the expression forming the array size into an id.
1957// This is not quite trivial, because of specialization constants.
1958// Sometimes, a raw constant is turned into an Id, and sometimes
1959// a specialization constant expression is.
1960spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1961{
1962 // First, see if this is sized with a node, meaning a specialization constant:
1963 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1964 if (specNode != nullptr) {
1965 builder.clearAccessChain();
1966 specNode->traverse(this);
1967 return accessChainLoad(specNode->getAsTyped()->getType());
1968 }
1969
1970 // Otherwise, need a compile-time (front end) size, get it:
1971 int size = arraySizes.getDimSize(dim);
1972 assert(size > 0);
1973 return builder.makeUintConstant(size);
1974}
1975
John Kessenich103bef92016-02-08 21:38:15 -07001976// Wrap the builder's accessChainLoad to:
1977// - localize handling of RelaxedPrecision
1978// - use the SPIR-V inferred type instead of another conversion of the glslang type
1979// (avoids unnecessary work and possible type punning for structures)
1980// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001981spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1982{
John Kessenich103bef92016-02-08 21:38:15 -07001983 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1984 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1985
1986 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001987 if (type.getBasicType() == glslang::EbtBool) {
1988 if (builder.isScalarType(nominalTypeId)) {
1989 // Conversion for bool
1990 spv::Id boolType = builder.makeBoolType();
1991 if (nominalTypeId != boolType)
1992 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1993 } else if (builder.isVectorType(nominalTypeId)) {
1994 // Conversion for bvec
1995 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1996 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1997 if (nominalTypeId != bvecType)
1998 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1999 }
2000 }
John Kessenich103bef92016-02-08 21:38:15 -07002001
2002 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002003}
2004
Rex Xu27253232016-02-23 17:51:09 +08002005// Wrap the builder's accessChainStore to:
2006// - do conversion of concrete to abstract type
2007void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2008{
2009 // Need to convert to abstract types when necessary
2010 if (type.getBasicType() == glslang::EbtBool) {
2011 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2012
2013 if (builder.isScalarType(nominalTypeId)) {
2014 // Conversion for bool
2015 spv::Id boolType = builder.makeBoolType();
2016 if (nominalTypeId != boolType) {
2017 spv::Id zero = builder.makeUintConstant(0);
2018 spv::Id one = builder.makeUintConstant(1);
2019 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2020 }
2021 } else if (builder.isVectorType(nominalTypeId)) {
2022 // Conversion for bvec
2023 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2024 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2025 if (nominalTypeId != bvecType) {
2026 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2027 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2028 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2029 }
2030 }
2031 }
2032
2033 builder.accessChainStore(rvalue);
2034}
2035
John Kessenichf85e8062015-12-19 13:57:10 -07002036// Decide whether or not this type should be
2037// decorated with offsets and strides, and if so
2038// whether std140 or std430 rules should be applied.
2039glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002040{
John Kessenichf85e8062015-12-19 13:57:10 -07002041 // has to be a block
2042 if (type.getBasicType() != glslang::EbtBlock)
2043 return glslang::ElpNone;
2044
2045 // has to be a uniform or buffer block
2046 if (type.getQualifier().storage != glslang::EvqUniform &&
2047 type.getQualifier().storage != glslang::EvqBuffer)
2048 return glslang::ElpNone;
2049
2050 // return the layout to use
2051 switch (type.getQualifier().layoutPacking) {
2052 case glslang::ElpStd140:
2053 case glslang::ElpStd430:
2054 return type.getQualifier().layoutPacking;
2055 default:
2056 return glslang::ElpNone;
2057 }
John Kessenich31ed4832015-09-09 17:51:38 -06002058}
2059
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002060// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002061int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002062{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002063 int size;
John Kessenich49987892015-12-29 17:11:44 -07002064 int stride;
2065 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002066
2067 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002068}
2069
John Kessenich49987892015-12-29 17:11:44 -07002070// 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 -07002071// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002072int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002073{
John Kessenich49987892015-12-29 17:11:44 -07002074 glslang::TType elementType;
2075 elementType.shallowCopy(matrixType);
2076 elementType.clearArraySizes();
2077
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002078 int size;
John Kessenich49987892015-12-29 17:11:44 -07002079 int stride;
2080 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2081
2082 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002083}
2084
John Kessenich5e4b1242015-08-06 22:53:06 -06002085// Given a member type of a struct, realign the current offset for it, and compute
2086// the next (not yet aligned) offset for the next member, which will get aligned
2087// on the next call.
2088// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2089// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2090// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002091void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002092 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002093{
2094 // this will get a positive value when deemed necessary
2095 nextOffset = -1;
2096
John Kessenich5e4b1242015-08-06 22:53:06 -06002097 // override anything in currentOffset with user-set offset
2098 if (memberType.getQualifier().hasOffset())
2099 currentOffset = memberType.getQualifier().layoutOffset;
2100
2101 // It could be that current linker usage in glslang updated all the layoutOffset,
2102 // in which case the following code does not matter. But, that's not quite right
2103 // once cross-compilation unit GLSL validation is done, as the original user
2104 // settings are needed in layoutOffset, and then the following will come into play.
2105
John Kessenichf85e8062015-12-19 13:57:10 -07002106 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002107 if (! memberType.getQualifier().hasOffset())
2108 currentOffset = -1;
2109
2110 return;
2111 }
2112
John Kessenichf85e8062015-12-19 13:57:10 -07002113 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002114 if (currentOffset < 0)
2115 currentOffset = 0;
2116
2117 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2118 // but possibly not yet correctly aligned.
2119
2120 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002121 int dummyStride;
2122 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002123 glslang::RoundToPow2(currentOffset, memberAlignment);
2124 nextOffset = currentOffset + memberSize;
2125}
2126
John Kessenich140f3df2015-06-26 16:58:36 -06002127bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2128{
John Kessenich4d65ee32016-03-12 18:17:47 -07002129 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002130 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002131 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002132}
2133
2134// Make all the functions, skeletally, without actually visiting their bodies.
2135void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2136{
2137 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2138 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2139 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2140 continue;
2141
2142 // We're on a user function. Set up the basic interface for the function now,
2143 // so that it's available to call.
2144 // Translating the body will happen later.
2145 //
2146 // Typically (except for a "const in" parameter), an address will be passed to the
2147 // function. What it is an address of varies:
2148 //
2149 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2150 // so that write needs to be to a copy, hence the address of a copy works.
2151 //
2152 // - "const in" parameters can just be the r-value, as no writes need occur.
2153 //
2154 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2155 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2156
2157 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002158 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002159 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2160
2161 for (int p = 0; p < (int)parameters.size(); ++p) {
2162 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2163 spv::Id typeId = convertGlslangToSpvType(paramType);
2164 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2165 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2166 else
2167 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002168 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002169 paramTypes.push_back(typeId);
2170 }
2171
2172 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002173 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2174 convertGlslangToSpvType(glslFunction->getType()),
2175 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002176
2177 // Track function to emit/call later
2178 functionMap[glslFunction->getName().c_str()] = function;
2179
2180 // Set the parameter id's
2181 for (int p = 0; p < (int)parameters.size(); ++p) {
2182 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2183 // give a name too
2184 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2185 }
2186 }
2187}
2188
2189// Process all the initializers, while skipping the functions and link objects
2190void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2191{
2192 builder.setBuildPoint(shaderEntry->getLastBlock());
2193 for (int i = 0; i < (int)initializers.size(); ++i) {
2194 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2195 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2196
2197 // We're on a top-level node that's not a function. Treat as an initializer, whose
2198 // code goes into the beginning of main.
2199 initializer->traverse(this);
2200 }
2201 }
2202}
2203
2204// Process all the functions, while skipping initializers.
2205void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2206{
2207 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2208 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2209 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2210 node->traverse(this);
2211 }
2212}
2213
2214void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2215{
2216 // SPIR-V functions should already be in the functionMap from the prepass
2217 // that called makeFunctions().
2218 spv::Function* function = functionMap[node->getName().c_str()];
2219 spv::Block* functionBlock = function->getEntryBlock();
2220 builder.setBuildPoint(functionBlock);
2221}
2222
Rex Xu04db3f52015-09-16 11:44:02 +08002223void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002224{
Rex Xufc618912015-09-09 16:42:49 +08002225 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002226
2227 glslang::TSampler sampler = {};
2228 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002229 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002230 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2231 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2232 }
2233
John Kessenich140f3df2015-06-26 16:58:36 -06002234 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2235 builder.clearAccessChain();
2236 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002237
2238 // Special case l-value operands
2239 bool lvalue = false;
2240 switch (node.getOp()) {
2241 case glslang::EOpImageAtomicAdd:
2242 case glslang::EOpImageAtomicMin:
2243 case glslang::EOpImageAtomicMax:
2244 case glslang::EOpImageAtomicAnd:
2245 case glslang::EOpImageAtomicOr:
2246 case glslang::EOpImageAtomicXor:
2247 case glslang::EOpImageAtomicExchange:
2248 case glslang::EOpImageAtomicCompSwap:
2249 if (i == 0)
2250 lvalue = true;
2251 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002252 case glslang::EOpSparseImageLoad:
2253 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2254 lvalue = true;
2255 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002256 case glslang::EOpSparseTexture:
2257 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2258 lvalue = true;
2259 break;
2260 case glslang::EOpSparseTextureClamp:
2261 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2262 lvalue = true;
2263 break;
2264 case glslang::EOpSparseTextureLod:
2265 case glslang::EOpSparseTextureOffset:
2266 if (i == 3)
2267 lvalue = true;
2268 break;
2269 case glslang::EOpSparseTextureFetch:
2270 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2271 lvalue = true;
2272 break;
2273 case glslang::EOpSparseTextureFetchOffset:
2274 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2275 lvalue = true;
2276 break;
2277 case glslang::EOpSparseTextureLodOffset:
2278 case glslang::EOpSparseTextureGrad:
2279 case glslang::EOpSparseTextureOffsetClamp:
2280 if (i == 4)
2281 lvalue = true;
2282 break;
2283 case glslang::EOpSparseTextureGradOffset:
2284 case glslang::EOpSparseTextureGradClamp:
2285 if (i == 5)
2286 lvalue = true;
2287 break;
2288 case glslang::EOpSparseTextureGradOffsetClamp:
2289 if (i == 6)
2290 lvalue = true;
2291 break;
2292 case glslang::EOpSparseTextureGather:
2293 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2294 lvalue = true;
2295 break;
2296 case glslang::EOpSparseTextureGatherOffset:
2297 case glslang::EOpSparseTextureGatherOffsets:
2298 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2299 lvalue = true;
2300 break;
Rex Xufc618912015-09-09 16:42:49 +08002301 default:
2302 break;
2303 }
2304
Rex Xu6b86d492015-09-16 17:48:22 +08002305 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002306 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002307 else
John Kessenich32cfd492016-02-02 12:37:46 -07002308 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002309 }
2310}
2311
John Kessenichfc51d282015-08-19 13:34:18 -06002312void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002313{
John Kessenichfc51d282015-08-19 13:34:18 -06002314 builder.clearAccessChain();
2315 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002316 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002317}
John Kessenich140f3df2015-06-26 16:58:36 -06002318
John Kessenichfc51d282015-08-19 13:34:18 -06002319spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2320{
Rex Xufc618912015-09-09 16:42:49 +08002321 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002322 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002323 }
2324
John Kessenichfc51d282015-08-19 13:34:18 -06002325 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002326 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2327 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2328 std::vector<spv::Id> arguments;
2329 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002330 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002331 else
2332 translateArguments(*node->getAsUnaryNode(), arguments);
2333 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2334
2335 spv::Builder::TextureParameters params = { };
2336 params.sampler = arguments[0];
2337
Rex Xu04db3f52015-09-16 11:44:02 +08002338 glslang::TCrackedTextureOp cracked;
2339 node->crackTexture(sampler, cracked);
2340
John Kessenichfc51d282015-08-19 13:34:18 -06002341 // Check for queries
2342 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002343 // a sampled image needs to have the image extracted first
2344 if (builder.isSampledImage(params.sampler))
2345 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002346 switch (node->getOp()) {
2347 case glslang::EOpImageQuerySize:
2348 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002349 if (arguments.size() > 1) {
2350 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002352 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002353 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002354 case glslang::EOpImageQuerySamples:
2355 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002356 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002357 case glslang::EOpTextureQueryLod:
2358 params.coords = arguments[1];
2359 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2360 case glslang::EOpTextureQueryLevels:
2361 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002362 case glslang::EOpSparseTexelsResident:
2363 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002364 default:
2365 assert(0);
2366 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002367 }
John Kessenich140f3df2015-06-26 16:58:36 -06002368 }
2369
Rex Xufc618912015-09-09 16:42:49 +08002370 // Check for image functions other than queries
2371 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002372 std::vector<spv::Id> operands;
2373 auto opIt = arguments.begin();
2374 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002375
2376 // Handle subpass operations
2377 // TODO: GLSL should change to have the "MS" only on the type rather than the
2378 // built-in function.
2379 if (cracked.subpass) {
2380 // add on the (0,0) coordinate
2381 spv::Id zero = builder.makeIntConstant(0);
2382 std::vector<spv::Id> comps;
2383 comps.push_back(zero);
2384 comps.push_back(zero);
2385 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2386 if (sampler.ms) {
2387 operands.push_back(spv::ImageOperandsSampleMask);
2388 operands.push_back(*(opIt++));
2389 }
2390 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2391 }
2392
John Kessenich56bab042015-09-16 10:54:31 -06002393 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002394 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002395 if (sampler.ms) {
2396 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002397 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002398 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002399 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2400 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002401 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002402 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002403 if (sampler.ms) {
2404 operands.push_back(*(opIt + 1));
2405 operands.push_back(spv::ImageOperandsSampleMask);
2406 operands.push_back(*opIt);
2407 } else
2408 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002409 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002410 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2411 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002412 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002413 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2414 builder.addCapability(spv::CapabilitySparseResidency);
2415 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2416 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2417
2418 if (sampler.ms) {
2419 operands.push_back(spv::ImageOperandsSampleMask);
2420 operands.push_back(*opIt++);
2421 }
2422
2423 // Create the return type that was a special structure
2424 spv::Id texelOut = *opIt;
2425 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2426 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2427 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2428
2429 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2430
2431 // Decode the return type
2432 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2433 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002434 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002435 // Process image atomic operations
2436
2437 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2438 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002439 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002440
Rex Xufc618912015-09-09 16:42:49 +08002441 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002442 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002443
2444 std::vector<spv::Id> operands;
2445 operands.push_back(pointer);
2446 for (; opIt != arguments.end(); ++opIt)
2447 operands.push_back(*opIt);
2448
Rex Xu04db3f52015-09-16 11:44:02 +08002449 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002450 }
2451 }
2452
2453 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002454 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002455 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2456
John Kessenichfc51d282015-08-19 13:34:18 -06002457 // check for bias argument
2458 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002459 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002460 int nonBiasArgCount = 2;
2461 if (cracked.offset)
2462 ++nonBiasArgCount;
2463 if (cracked.grad)
2464 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002465 if (cracked.lodClamp)
2466 ++nonBiasArgCount;
2467 if (sparse)
2468 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002469
2470 if ((int)arguments.size() > nonBiasArgCount)
2471 bias = true;
2472 }
2473
John Kessenichfc51d282015-08-19 13:34:18 -06002474 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002475
John Kessenichfc51d282015-08-19 13:34:18 -06002476 params.coords = arguments[1];
2477 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002478 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002479
2480 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002481 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002482 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002483 ++extraArgs;
2484 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002485 params.Dref = arguments[2];
2486 ++extraArgs;
2487 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002488 std::vector<spv::Id> indexes;
2489 int comp;
2490 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002491 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002492 else
2493 comp = builder.getNumComponents(params.coords) - 1;
2494 indexes.push_back(comp);
2495 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2496 }
2497 if (cracked.lod) {
2498 params.lod = arguments[2];
2499 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002500 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2501 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2502 noImplicitLod = true;
2503 }
2504 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002505 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002506 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002507 }
2508 if (cracked.grad) {
2509 params.gradX = arguments[2 + extraArgs];
2510 params.gradY = arguments[3 + extraArgs];
2511 extraArgs += 2;
2512 }
John Kessenich55e7d112015-11-15 21:33:39 -07002513 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002514 params.offset = arguments[2 + extraArgs];
2515 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002516 } else if (cracked.offsets) {
2517 params.offsets = arguments[2 + extraArgs];
2518 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002519 }
Rex Xu48edadf2015-12-31 16:11:41 +08002520 if (cracked.lodClamp) {
2521 params.lodClamp = arguments[2 + extraArgs];
2522 ++extraArgs;
2523 }
2524 if (sparse) {
2525 params.texelOut = arguments[2 + extraArgs];
2526 ++extraArgs;
2527 }
John Kessenichfc51d282015-08-19 13:34:18 -06002528 if (bias) {
2529 params.bias = arguments[2 + extraArgs];
2530 ++extraArgs;
2531 }
John Kessenich55e7d112015-11-15 21:33:39 -07002532 if (cracked.gather && ! sampler.shadow) {
2533 // default component is 0, if missing, otherwise an argument
2534 if (2 + extraArgs < (int)arguments.size()) {
2535 params.comp = arguments[2 + extraArgs];
2536 ++extraArgs;
2537 } else {
2538 params.comp = builder.makeIntConstant(0);
2539 }
2540 }
John Kessenichfc51d282015-08-19 13:34:18 -06002541
John Kessenich019f08f2016-02-15 15:40:42 -07002542 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002543}
2544
2545spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2546{
2547 // Grab the function's pointer from the previously created function
2548 spv::Function* function = functionMap[node->getName().c_str()];
2549 if (! function)
2550 return 0;
2551
2552 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2553 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2554
2555 // See comments in makeFunctions() for details about the semantics for parameter passing.
2556 //
2557 // These imply we need a four step process:
2558 // 1. Evaluate the arguments
2559 // 2. Allocate and make copies of in, out, and inout arguments
2560 // 3. Make the call
2561 // 4. Copy back the results
2562
2563 // 1. Evaluate the arguments
2564 std::vector<spv::Builder::AccessChain> lValues;
2565 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002566 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002567 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2568 // build l-value
2569 builder.clearAccessChain();
2570 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002571 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002572 // keep outputs as l-values, evaluate input-only as r-values
2573 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2574 // save l-value
2575 lValues.push_back(builder.getAccessChain());
2576 } else {
2577 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002578 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002579 }
2580 }
2581
2582 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2583 // copy the original into that space.
2584 //
2585 // Also, build up the list of actual arguments to pass in for the call
2586 int lValueCount = 0;
2587 int rValueCount = 0;
2588 std::vector<spv::Id> spvArgs;
2589 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2590 spv::Id arg;
2591 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2592 // need space to hold the copy
2593 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2594 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2595 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2596 // need to copy the input into output space
2597 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002598 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002599 builder.createStore(copy, arg);
2600 }
2601 ++lValueCount;
2602 } else {
2603 arg = rValues[rValueCount];
2604 ++rValueCount;
2605 }
2606 spvArgs.push_back(arg);
2607 }
2608
2609 // 3. Make the call.
2610 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002611 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002612
2613 // 4. Copy back out an "out" arguments.
2614 lValueCount = 0;
2615 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2616 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2617 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2618 spv::Id copy = builder.createLoad(spvArgs[a]);
2619 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002620 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002621 }
2622 ++lValueCount;
2623 }
2624 }
2625
2626 return result;
2627}
2628
2629// Translate AST operation to SPV operation, already having SPV-based operands/types.
2630spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2631 spv::Id typeId, spv::Id left, spv::Id right,
2632 glslang::TBasicType typeProxy, bool reduceComparison)
2633{
2634 bool isUnsigned = typeProxy == glslang::EbtUint;
2635 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2636
2637 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002638 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002639 bool comparison = false;
2640
2641 switch (op) {
2642 case glslang::EOpAdd:
2643 case glslang::EOpAddAssign:
2644 if (isFloat)
2645 binOp = spv::OpFAdd;
2646 else
2647 binOp = spv::OpIAdd;
2648 break;
2649 case glslang::EOpSub:
2650 case glslang::EOpSubAssign:
2651 if (isFloat)
2652 binOp = spv::OpFSub;
2653 else
2654 binOp = spv::OpISub;
2655 break;
2656 case glslang::EOpMul:
2657 case glslang::EOpMulAssign:
2658 if (isFloat)
2659 binOp = spv::OpFMul;
2660 else
2661 binOp = spv::OpIMul;
2662 break;
2663 case glslang::EOpVectorTimesScalar:
2664 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002665 if (isFloat) {
2666 if (builder.isVector(right))
2667 std::swap(left, right);
2668 assert(builder.isScalar(right));
2669 needMatchingVectors = false;
2670 binOp = spv::OpVectorTimesScalar;
2671 } else
2672 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002673 break;
2674 case glslang::EOpVectorTimesMatrix:
2675 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002676 binOp = spv::OpVectorTimesMatrix;
2677 break;
2678 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002679 binOp = spv::OpMatrixTimesVector;
2680 break;
2681 case glslang::EOpMatrixTimesScalar:
2682 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002683 binOp = spv::OpMatrixTimesScalar;
2684 break;
2685 case glslang::EOpMatrixTimesMatrix:
2686 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002687 binOp = spv::OpMatrixTimesMatrix;
2688 break;
2689 case glslang::EOpOuterProduct:
2690 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002691 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002692 break;
2693
2694 case glslang::EOpDiv:
2695 case glslang::EOpDivAssign:
2696 if (isFloat)
2697 binOp = spv::OpFDiv;
2698 else if (isUnsigned)
2699 binOp = spv::OpUDiv;
2700 else
2701 binOp = spv::OpSDiv;
2702 break;
2703 case glslang::EOpMod:
2704 case glslang::EOpModAssign:
2705 if (isFloat)
2706 binOp = spv::OpFMod;
2707 else if (isUnsigned)
2708 binOp = spv::OpUMod;
2709 else
2710 binOp = spv::OpSMod;
2711 break;
2712 case glslang::EOpRightShift:
2713 case glslang::EOpRightShiftAssign:
2714 if (isUnsigned)
2715 binOp = spv::OpShiftRightLogical;
2716 else
2717 binOp = spv::OpShiftRightArithmetic;
2718 break;
2719 case glslang::EOpLeftShift:
2720 case glslang::EOpLeftShiftAssign:
2721 binOp = spv::OpShiftLeftLogical;
2722 break;
2723 case glslang::EOpAnd:
2724 case glslang::EOpAndAssign:
2725 binOp = spv::OpBitwiseAnd;
2726 break;
2727 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002728 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002729 binOp = spv::OpLogicalAnd;
2730 break;
2731 case glslang::EOpInclusiveOr:
2732 case glslang::EOpInclusiveOrAssign:
2733 binOp = spv::OpBitwiseOr;
2734 break;
2735 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002736 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002737 binOp = spv::OpLogicalOr;
2738 break;
2739 case glslang::EOpExclusiveOr:
2740 case glslang::EOpExclusiveOrAssign:
2741 binOp = spv::OpBitwiseXor;
2742 break;
2743 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002744 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 break;
2747
2748 case glslang::EOpLessThan:
2749 case glslang::EOpGreaterThan:
2750 case glslang::EOpLessThanEqual:
2751 case glslang::EOpGreaterThanEqual:
2752 case glslang::EOpEqual:
2753 case glslang::EOpNotEqual:
2754 case glslang::EOpVectorEqual:
2755 case glslang::EOpVectorNotEqual:
2756 comparison = true;
2757 break;
2758 default:
2759 break;
2760 }
2761
John Kessenich7c1aa102015-10-15 13:29:11 -06002762 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002763 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002764 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002765 if (builder.isMatrix(left) || builder.isMatrix(right))
2766 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002767
2768 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002769 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002770 builder.promoteScalar(precision, left, right);
2771
John Kessenich32cfd492016-02-02 12:37:46 -07002772 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002773 }
2774
2775 if (! comparison)
2776 return 0;
2777
John Kessenich7c1aa102015-10-15 13:29:11 -06002778 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002779
2780 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2781 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2782
John Kessenich22118352015-12-21 20:54:09 -07002783 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002784 }
2785
2786 switch (op) {
2787 case glslang::EOpLessThan:
2788 if (isFloat)
2789 binOp = spv::OpFOrdLessThan;
2790 else if (isUnsigned)
2791 binOp = spv::OpULessThan;
2792 else
2793 binOp = spv::OpSLessThan;
2794 break;
2795 case glslang::EOpGreaterThan:
2796 if (isFloat)
2797 binOp = spv::OpFOrdGreaterThan;
2798 else if (isUnsigned)
2799 binOp = spv::OpUGreaterThan;
2800 else
2801 binOp = spv::OpSGreaterThan;
2802 break;
2803 case glslang::EOpLessThanEqual:
2804 if (isFloat)
2805 binOp = spv::OpFOrdLessThanEqual;
2806 else if (isUnsigned)
2807 binOp = spv::OpULessThanEqual;
2808 else
2809 binOp = spv::OpSLessThanEqual;
2810 break;
2811 case glslang::EOpGreaterThanEqual:
2812 if (isFloat)
2813 binOp = spv::OpFOrdGreaterThanEqual;
2814 else if (isUnsigned)
2815 binOp = spv::OpUGreaterThanEqual;
2816 else
2817 binOp = spv::OpSGreaterThanEqual;
2818 break;
2819 case glslang::EOpEqual:
2820 case glslang::EOpVectorEqual:
2821 if (isFloat)
2822 binOp = spv::OpFOrdEqual;
2823 else
2824 binOp = spv::OpIEqual;
2825 break;
2826 case glslang::EOpNotEqual:
2827 case glslang::EOpVectorNotEqual:
2828 if (isFloat)
2829 binOp = spv::OpFOrdNotEqual;
2830 else
2831 binOp = spv::OpINotEqual;
2832 break;
2833 default:
2834 break;
2835 }
2836
John Kessenich32cfd492016-02-02 12:37:46 -07002837 if (binOp != spv::OpNop)
2838 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002839
2840 return 0;
2841}
2842
John Kessenich04bb8a02015-12-12 12:28:14 -07002843//
2844// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2845// These can be any of:
2846//
2847// matrix * scalar
2848// scalar * matrix
2849// matrix * matrix linear algebraic
2850// matrix * vector
2851// vector * matrix
2852// matrix * matrix componentwise
2853// matrix op matrix op in {+, -, /}
2854// matrix op scalar op in {+, -, /}
2855// scalar op matrix op in {+, -, /}
2856//
2857spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2858{
2859 bool firstClass = true;
2860
2861 // First, handle first-class matrix operations (* and matrix/scalar)
2862 switch (op) {
2863 case spv::OpFDiv:
2864 if (builder.isMatrix(left) && builder.isScalar(right)) {
2865 // turn matrix / scalar into a multiply...
2866 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2867 op = spv::OpMatrixTimesScalar;
2868 } else
2869 firstClass = false;
2870 break;
2871 case spv::OpMatrixTimesScalar:
2872 if (builder.isMatrix(right))
2873 std::swap(left, right);
2874 assert(builder.isScalar(right));
2875 break;
2876 case spv::OpVectorTimesMatrix:
2877 assert(builder.isVector(left));
2878 assert(builder.isMatrix(right));
2879 break;
2880 case spv::OpMatrixTimesVector:
2881 assert(builder.isMatrix(left));
2882 assert(builder.isVector(right));
2883 break;
2884 case spv::OpMatrixTimesMatrix:
2885 assert(builder.isMatrix(left));
2886 assert(builder.isMatrix(right));
2887 break;
2888 default:
2889 firstClass = false;
2890 break;
2891 }
2892
John Kessenich32cfd492016-02-02 12:37:46 -07002893 if (firstClass)
2894 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002895
2896 // Handle component-wise +, -, *, and / for all combinations of type.
2897 // The result type of all of them is the same type as the (a) matrix operand.
2898 // The algorithm is to:
2899 // - break the matrix(es) into vectors
2900 // - smear any scalar to a vector
2901 // - do vector operations
2902 // - make a matrix out the vector results
2903 switch (op) {
2904 case spv::OpFAdd:
2905 case spv::OpFSub:
2906 case spv::OpFDiv:
2907 case spv::OpFMul:
2908 {
2909 // one time set up...
2910 bool leftMat = builder.isMatrix(left);
2911 bool rightMat = builder.isMatrix(right);
2912 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2913 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2914 spv::Id scalarType = builder.getScalarTypeId(typeId);
2915 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2916 std::vector<spv::Id> results;
2917 spv::Id smearVec = spv::NoResult;
2918 if (builder.isScalar(left))
2919 smearVec = builder.smearScalar(precision, left, vecType);
2920 else if (builder.isScalar(right))
2921 smearVec = builder.smearScalar(precision, right, vecType);
2922
2923 // do each vector op
2924 for (unsigned int c = 0; c < numCols; ++c) {
2925 std::vector<unsigned int> indexes;
2926 indexes.push_back(c);
2927 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2928 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2929 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2930 builder.setPrecision(results.back(), precision);
2931 }
2932
2933 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002934 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002935 }
2936 default:
2937 assert(0);
2938 return spv::NoResult;
2939 }
2940}
2941
Rex Xu04db3f52015-09-16 11:44:02 +08002942spv::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 -06002943{
2944 spv::Op unaryOp = spv::OpNop;
2945 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002946 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002947 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002948
2949 switch (op) {
2950 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002951 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002952 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002953 if (builder.isMatrixType(typeId))
2954 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2955 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002956 unaryOp = spv::OpSNegate;
2957 break;
2958
2959 case glslang::EOpLogicalNot:
2960 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002961 unaryOp = spv::OpLogicalNot;
2962 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 case glslang::EOpBitwiseNot:
2964 unaryOp = spv::OpNot;
2965 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002966
John Kessenich140f3df2015-06-26 16:58:36 -06002967 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 break;
2973 case glslang::EOpTranspose:
2974 unaryOp = spv::OpTranspose;
2975 break;
2976
2977 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
2983 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002984 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 break;
2986 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 break;
2989 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002997 break;
2998 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002999 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003000 break;
3001
3002 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 break;
3014 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003015 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003016 break;
3017 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003018 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003019 break;
3020
3021 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027
3028 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003029 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003030 break;
3031 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003032 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 break;
3034 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046
3047 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003048 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 break;
3050 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003051 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003052 break;
3053 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003054 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003055 break;
3056 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003057 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003058 break;
3059 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003060 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003061 break;
3062 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003063 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003064 break;
3065
3066 case glslang::EOpIsNan:
3067 unaryOp = spv::OpIsNan;
3068 break;
3069 case glslang::EOpIsInf:
3070 unaryOp = spv::OpIsInf;
3071 break;
3072
Rex Xucbc426e2015-12-15 16:03:10 +08003073 case glslang::EOpFloatBitsToInt:
3074 case glslang::EOpFloatBitsToUint:
3075 case glslang::EOpIntBitsToFloat:
3076 case glslang::EOpUintBitsToFloat:
3077 unaryOp = spv::OpBitcast;
3078 break;
3079
John Kessenich140f3df2015-06-26 16:58:36 -06003080 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003081 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003082 break;
3083 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003084 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003085 break;
3086 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003087 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003090 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 break;
3092 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003093 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003094 break;
3095 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003096 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003097 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003098 case glslang::EOpPackSnorm4x8:
3099 libCall = spv::GLSLstd450PackSnorm4x8;
3100 break;
3101 case glslang::EOpUnpackSnorm4x8:
3102 libCall = spv::GLSLstd450UnpackSnorm4x8;
3103 break;
3104 case glslang::EOpPackUnorm4x8:
3105 libCall = spv::GLSLstd450PackUnorm4x8;
3106 break;
3107 case glslang::EOpUnpackUnorm4x8:
3108 libCall = spv::GLSLstd450UnpackUnorm4x8;
3109 break;
3110 case glslang::EOpPackDouble2x32:
3111 libCall = spv::GLSLstd450PackDouble2x32;
3112 break;
3113 case glslang::EOpUnpackDouble2x32:
3114 libCall = spv::GLSLstd450UnpackDouble2x32;
3115 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003116
3117 case glslang::EOpDPdx:
3118 unaryOp = spv::OpDPdx;
3119 break;
3120 case glslang::EOpDPdy:
3121 unaryOp = spv::OpDPdy;
3122 break;
3123 case glslang::EOpFwidth:
3124 unaryOp = spv::OpFwidth;
3125 break;
3126 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003127 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003128 unaryOp = spv::OpDPdxFine;
3129 break;
3130 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003131 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003132 unaryOp = spv::OpDPdyFine;
3133 break;
3134 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003135 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003136 unaryOp = spv::OpFwidthFine;
3137 break;
3138 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003139 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003140 unaryOp = spv::OpDPdxCoarse;
3141 break;
3142 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003143 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003144 unaryOp = spv::OpDPdyCoarse;
3145 break;
3146 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003147 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003148 unaryOp = spv::OpFwidthCoarse;
3149 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003150 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003151 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003152 libCall = spv::GLSLstd450InterpolateAtCentroid;
3153 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 case glslang::EOpAny:
3155 unaryOp = spv::OpAny;
3156 break;
3157 case glslang::EOpAll:
3158 unaryOp = spv::OpAll;
3159 break;
3160
3161 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003162 if (isFloat)
3163 libCall = spv::GLSLstd450FAbs;
3164 else
3165 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 if (isFloat)
3169 libCall = spv::GLSLstd450FSign;
3170 else
3171 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
3173
John Kessenichfc51d282015-08-19 13:34:18 -06003174 case glslang::EOpAtomicCounterIncrement:
3175 case glslang::EOpAtomicCounterDecrement:
3176 case glslang::EOpAtomicCounter:
3177 {
3178 // Handle all of the atomics in one place, in createAtomicOperation()
3179 std::vector<spv::Id> operands;
3180 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003181 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003182 }
3183
John Kessenichfc51d282015-08-19 13:34:18 -06003184 case glslang::EOpBitFieldReverse:
3185 unaryOp = spv::OpBitReverse;
3186 break;
3187 case glslang::EOpBitCount:
3188 unaryOp = spv::OpBitCount;
3189 break;
3190 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003191 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003192 break;
3193 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003194 if (isUnsigned)
3195 libCall = spv::GLSLstd450FindUMsb;
3196 else
3197 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003198 break;
3199
John Kessenich140f3df2015-06-26 16:58:36 -06003200 default:
3201 return 0;
3202 }
3203
3204 spv::Id id;
3205 if (libCall >= 0) {
3206 std::vector<spv::Id> args;
3207 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003208 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003209 } else
3210 id = builder.createUnaryOp(unaryOp, typeId, operand);
3211
John Kessenich32cfd492016-02-02 12:37:46 -07003212 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003213}
3214
John Kessenich7a53f762016-01-20 11:19:27 -07003215// Create a unary operation on a matrix
3216spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3217{
3218 // Handle unary operations vector by vector.
3219 // The result type is the same type as the original type.
3220 // The algorithm is to:
3221 // - break the matrix into vectors
3222 // - apply the operation to each vector
3223 // - make a matrix out the vector results
3224
3225 // get the types sorted out
3226 int numCols = builder.getNumColumns(operand);
3227 int numRows = builder.getNumRows(operand);
3228 spv::Id scalarType = builder.getScalarTypeId(typeId);
3229 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3230 std::vector<spv::Id> results;
3231
3232 // do each vector op
3233 for (int c = 0; c < numCols; ++c) {
3234 std::vector<unsigned int> indexes;
3235 indexes.push_back(c);
3236 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3237 results.push_back(builder.createUnaryOp(op, vecType, vec));
3238 builder.setPrecision(results.back(), precision);
3239 }
3240
3241 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003242 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003243}
3244
John Kessenich140f3df2015-06-26 16:58:36 -06003245spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3246{
3247 spv::Op convOp = spv::OpNop;
3248 spv::Id zero = 0;
3249 spv::Id one = 0;
3250
3251 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3252
3253 switch (op) {
3254 case glslang::EOpConvIntToBool:
3255 case glslang::EOpConvUintToBool:
3256 zero = builder.makeUintConstant(0);
3257 zero = makeSmearedConstant(zero, vectorSize);
3258 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3259
3260 case glslang::EOpConvFloatToBool:
3261 zero = builder.makeFloatConstant(0.0F);
3262 zero = makeSmearedConstant(zero, vectorSize);
3263 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3264
3265 case glslang::EOpConvDoubleToBool:
3266 zero = builder.makeDoubleConstant(0.0);
3267 zero = makeSmearedConstant(zero, vectorSize);
3268 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3269
3270 case glslang::EOpConvBoolToFloat:
3271 convOp = spv::OpSelect;
3272 zero = builder.makeFloatConstant(0.0);
3273 one = builder.makeFloatConstant(1.0);
3274 break;
3275 case glslang::EOpConvBoolToDouble:
3276 convOp = spv::OpSelect;
3277 zero = builder.makeDoubleConstant(0.0);
3278 one = builder.makeDoubleConstant(1.0);
3279 break;
3280 case glslang::EOpConvBoolToInt:
3281 zero = builder.makeIntConstant(0);
3282 one = builder.makeIntConstant(1);
3283 convOp = spv::OpSelect;
3284 break;
3285 case glslang::EOpConvBoolToUint:
3286 zero = builder.makeUintConstant(0);
3287 one = builder.makeUintConstant(1);
3288 convOp = spv::OpSelect;
3289 break;
3290
3291 case glslang::EOpConvIntToFloat:
3292 case glslang::EOpConvIntToDouble:
3293 convOp = spv::OpConvertSToF;
3294 break;
3295
3296 case glslang::EOpConvUintToFloat:
3297 case glslang::EOpConvUintToDouble:
3298 convOp = spv::OpConvertUToF;
3299 break;
3300
3301 case glslang::EOpConvDoubleToFloat:
3302 case glslang::EOpConvFloatToDouble:
3303 convOp = spv::OpFConvert;
3304 break;
3305
3306 case glslang::EOpConvFloatToInt:
3307 case glslang::EOpConvDoubleToInt:
3308 convOp = spv::OpConvertFToS;
3309 break;
3310
3311 case glslang::EOpConvUintToInt:
3312 case glslang::EOpConvIntToUint:
qininge24aa5e2016-04-07 15:40:27 -04003313 if (builder.isInSpecConstCodeGenMode()) {
3314 // Build zero scalar or vector for OpIAdd.
qining189b2032016-04-12 23:16:20 -04003315 zero = builder.makeUintConstant(0);
3316 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003317 // Use OpIAdd, instead of OpBitcast to do the conversion when
3318 // generating for OpSpecConstantOp instruction.
3319 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3320 }
3321 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003322 convOp = spv::OpBitcast;
3323 break;
3324
3325 case glslang::EOpConvFloatToUint:
3326 case glslang::EOpConvDoubleToUint:
3327 convOp = spv::OpConvertFToU;
3328 break;
3329 default:
3330 break;
3331 }
3332
3333 spv::Id result = 0;
3334 if (convOp == spv::OpNop)
3335 return result;
3336
3337 if (convOp == spv::OpSelect) {
3338 zero = makeSmearedConstant(zero, vectorSize);
3339 one = makeSmearedConstant(one, vectorSize);
3340 result = builder.createTriOp(convOp, destType, operand, one, zero);
3341 } else
3342 result = builder.createUnaryOp(convOp, destType, operand);
3343
John Kessenich32cfd492016-02-02 12:37:46 -07003344 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003345}
3346
3347spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3348{
3349 if (vectorSize == 0)
3350 return constant;
3351
3352 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3353 std::vector<spv::Id> components;
3354 for (int c = 0; c < vectorSize; ++c)
3355 components.push_back(constant);
3356 return builder.makeCompositeConstant(vectorTypeId, components);
3357}
3358
John Kessenich426394d2015-07-23 10:22:48 -06003359// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003360spv::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 -06003361{
3362 spv::Op opCode = spv::OpNop;
3363
3364 switch (op) {
3365 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003366 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003367 opCode = spv::OpAtomicIAdd;
3368 break;
3369 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003370 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003371 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003372 break;
3373 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003374 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003375 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003376 break;
3377 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003378 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003379 opCode = spv::OpAtomicAnd;
3380 break;
3381 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003382 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003383 opCode = spv::OpAtomicOr;
3384 break;
3385 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003386 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003387 opCode = spv::OpAtomicXor;
3388 break;
3389 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003390 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003391 opCode = spv::OpAtomicExchange;
3392 break;
3393 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003394 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003395 opCode = spv::OpAtomicCompareExchange;
3396 break;
3397 case glslang::EOpAtomicCounterIncrement:
3398 opCode = spv::OpAtomicIIncrement;
3399 break;
3400 case glslang::EOpAtomicCounterDecrement:
3401 opCode = spv::OpAtomicIDecrement;
3402 break;
3403 case glslang::EOpAtomicCounter:
3404 opCode = spv::OpAtomicLoad;
3405 break;
3406 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003407 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003408 break;
3409 }
3410
3411 // Sort out the operands
3412 // - mapping from glslang -> SPV
3413 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003414 // - compare-exchange swaps the value and comparator
3415 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003416 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3417 auto opIt = operands.begin(); // walk the glslang operands
3418 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003419 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3420 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3421 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003422 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3423 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003424 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003425 spvAtomicOperands.push_back(*(opIt + 1));
3426 spvAtomicOperands.push_back(*opIt);
3427 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003428 }
John Kessenich426394d2015-07-23 10:22:48 -06003429
John Kessenich3e60a6f2015-09-14 22:45:16 -06003430 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003431 for (; opIt != operands.end(); ++opIt)
3432 spvAtomicOperands.push_back(*opIt);
3433
3434 return builder.createOp(opCode, typeId, spvAtomicOperands);
3435}
3436
John Kessenich5e4b1242015-08-06 22:53:06 -06003437spv::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 -06003438{
John Kessenich5e4b1242015-08-06 22:53:06 -06003439 bool isUnsigned = typeProxy == glslang::EbtUint;
3440 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3441
John Kessenich140f3df2015-06-26 16:58:36 -06003442 spv::Op opCode = spv::OpNop;
3443 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003444 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003445 spv::Id typeId0 = 0;
3446 if (consumedOperands > 0)
3447 typeId0 = builder.getTypeId(operands[0]);
3448 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003449
3450 switch (op) {
3451 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003452 if (isFloat)
3453 libCall = spv::GLSLstd450FMin;
3454 else if (isUnsigned)
3455 libCall = spv::GLSLstd450UMin;
3456 else
3457 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003458 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003459 break;
3460 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003461 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003462 break;
3463 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003464 if (isFloat)
3465 libCall = spv::GLSLstd450FMax;
3466 else if (isUnsigned)
3467 libCall = spv::GLSLstd450UMax;
3468 else
3469 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003470 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
3472 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003474 break;
3475 case glslang::EOpDot:
3476 opCode = spv::OpDot;
3477 break;
3478 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481
3482 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003483 if (isFloat)
3484 libCall = spv::GLSLstd450FClamp;
3485 else if (isUnsigned)
3486 libCall = spv::GLSLstd450UClamp;
3487 else
3488 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003489 builder.promoteScalar(precision, operands.front(), operands[1]);
3490 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003493 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3494 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003495 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003496 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003497 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003498 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003499 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003500 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003504 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003505 break;
3506 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003507 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003508 builder.promoteScalar(precision, operands[0], operands[2]);
3509 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003510 break;
3511
3512 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003513 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 break;
3515 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 break;
3524 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003527 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003528 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003529 libCall = spv::GLSLstd450InterpolateAtSample;
3530 break;
3531 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003532 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003533 libCall = spv::GLSLstd450InterpolateAtOffset;
3534 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003535 case glslang::EOpAddCarry:
3536 opCode = spv::OpIAddCarry;
3537 typeId = builder.makeStructResultType(typeId0, typeId0);
3538 consumedOperands = 2;
3539 break;
3540 case glslang::EOpSubBorrow:
3541 opCode = spv::OpISubBorrow;
3542 typeId = builder.makeStructResultType(typeId0, typeId0);
3543 consumedOperands = 2;
3544 break;
3545 case glslang::EOpUMulExtended:
3546 opCode = spv::OpUMulExtended;
3547 typeId = builder.makeStructResultType(typeId0, typeId0);
3548 consumedOperands = 2;
3549 break;
3550 case glslang::EOpIMulExtended:
3551 opCode = spv::OpSMulExtended;
3552 typeId = builder.makeStructResultType(typeId0, typeId0);
3553 consumedOperands = 2;
3554 break;
3555 case glslang::EOpBitfieldExtract:
3556 if (isUnsigned)
3557 opCode = spv::OpBitFieldUExtract;
3558 else
3559 opCode = spv::OpBitFieldSExtract;
3560 break;
3561 case glslang::EOpBitfieldInsert:
3562 opCode = spv::OpBitFieldInsert;
3563 break;
3564
3565 case glslang::EOpFma:
3566 libCall = spv::GLSLstd450Fma;
3567 break;
3568 case glslang::EOpFrexp:
3569 libCall = spv::GLSLstd450FrexpStruct;
3570 if (builder.getNumComponents(operands[0]) == 1)
3571 frexpIntType = builder.makeIntegerType(32, true);
3572 else
3573 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3574 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3575 consumedOperands = 1;
3576 break;
3577 case glslang::EOpLdexp:
3578 libCall = spv::GLSLstd450Ldexp;
3579 break;
3580
John Kessenich140f3df2015-06-26 16:58:36 -06003581 default:
3582 return 0;
3583 }
3584
3585 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003586 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003587 // Use an extended instruction from the standard library.
3588 // Construct the call arguments, without modifying the original operands vector.
3589 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3590 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003591 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003592 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003593 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003594 case 0:
3595 // should all be handled by visitAggregate and createNoArgOperation
3596 assert(0);
3597 return 0;
3598 case 1:
3599 // should all be handled by createUnaryOperation
3600 assert(0);
3601 return 0;
3602 case 2:
3603 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3604 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003606 // anything 3 or over doesn't have l-value operands, so all should be consumed
3607 assert(consumedOperands == operands.size());
3608 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003609 break;
3610 }
3611 }
3612
John Kessenich55e7d112015-11-15 21:33:39 -07003613 // Decode the return types that were structures
3614 switch (op) {
3615 case glslang::EOpAddCarry:
3616 case glslang::EOpSubBorrow:
3617 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3618 id = builder.createCompositeExtract(id, typeId0, 0);
3619 break;
3620 case glslang::EOpUMulExtended:
3621 case glslang::EOpIMulExtended:
3622 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3623 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3624 break;
3625 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003626 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003627 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3628 id = builder.createCompositeExtract(id, typeId0, 0);
3629 break;
3630 default:
3631 break;
3632 }
3633
John Kessenich32cfd492016-02-02 12:37:46 -07003634 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003635}
3636
3637// Intrinsics with no arguments, no return value, and no precision.
3638spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3639{
3640 // TODO: get the barrier operands correct
3641
3642 switch (op) {
3643 case glslang::EOpEmitVertex:
3644 builder.createNoResultOp(spv::OpEmitVertex);
3645 return 0;
3646 case glslang::EOpEndPrimitive:
3647 builder.createNoResultOp(spv::OpEndPrimitive);
3648 return 0;
3649 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003650 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3651 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003652 return 0;
3653 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003654 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003655 return 0;
3656 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003657 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003658 return 0;
3659 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003661 return 0;
3662 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003663 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003664 return 0;
3665 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003666 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003667 return 0;
3668 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003669 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003670 return 0;
3671 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003672 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003673 return 0;
3674 }
3675}
3676
3677spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3678{
John Kessenich2f273362015-07-18 22:34:27 -06003679 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003680 spv::Id id;
3681 if (symbolValues.end() != iter) {
3682 id = iter->second;
3683 return id;
3684 }
3685
3686 // it was not found, create it
3687 id = createSpvVariable(symbol);
3688 symbolValues[symbol->getId()] = id;
3689
3690 if (! symbol->getType().isStruct()) {
3691 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003692 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003693 if (symbol->getType().getQualifier().hasSpecConstantId())
3694 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003695 if (symbol->getQualifier().hasLocation())
3696 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3697 if (symbol->getQualifier().hasIndex())
3698 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3699 if (symbol->getQualifier().hasComponent())
3700 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3701 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003702 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003703 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003704 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003705 if (symbol->getQualifier().hasXfbBuffer())
3706 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3707 if (symbol->getQualifier().hasXfbOffset())
3708 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3709 }
3710 }
3711
John Kesseniche0b6cad2015-12-24 10:30:13 -07003712 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003713 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003714 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003715 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003716 }
John Kessenich140f3df2015-06-26 16:58:36 -06003717 if (symbol->getQualifier().hasSet())
3718 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003719 else if (IsDescriptorResource(symbol->getType())) {
3720 // default to 0
3721 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3722 }
John Kessenich140f3df2015-06-26 16:58:36 -06003723 if (symbol->getQualifier().hasBinding())
3724 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003725 if (symbol->getQualifier().hasAttachment())
3726 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003727 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003728 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003729 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003731 if (symbol->getQualifier().hasXfbBuffer())
3732 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3733 }
3734
Rex Xu1da878f2016-02-21 20:59:01 +08003735 if (symbol->getType().isImage()) {
3736 std::vector<spv::Decoration> memory;
3737 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3738 for (unsigned int i = 0; i < memory.size(); ++i)
3739 addDecoration(id, memory[i]);
3740 }
3741
John Kessenich140f3df2015-06-26 16:58:36 -06003742 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003743 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003745 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003746
John Kessenich140f3df2015-06-26 16:58:36 -06003747 return id;
3748}
3749
John Kessenich55e7d112015-11-15 21:33:39 -07003750// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003751void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3752{
3753 if (dec != spv::BadValue)
3754 builder.addDecoration(id, dec);
3755}
3756
John Kessenich55e7d112015-11-15 21:33:39 -07003757// If 'dec' is valid, add a one-operand decoration to an object
3758void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3759{
3760 if (dec != spv::BadValue)
3761 builder.addDecoration(id, dec, value);
3762}
3763
3764// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003765void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3766{
3767 if (dec != spv::BadValue)
3768 builder.addMemberDecoration(id, (unsigned)member, dec);
3769}
3770
John Kessenich92187592016-02-01 13:45:25 -07003771// If 'dec' is valid, add a one-operand decoration to a struct member
3772void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3773{
3774 if (dec != spv::BadValue)
3775 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3776}
3777
John Kessenich55e7d112015-11-15 21:33:39 -07003778// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003779// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003780//
3781// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3782//
3783// Recursively walk the nodes. The nodes form a tree whose leaves are
3784// regular constants, which themselves are trees that createSpvConstant()
3785// recursively walks. So, this function walks the "top" of the tree:
3786// - emit specialization constant-building instructions for specConstant
3787// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003788spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003789{
John Kessenich7cc0e282016-03-20 00:46:02 -06003790 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003791
qining4f4bb812016-04-03 23:55:17 -04003792 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003793 if (! node.getQualifier().specConstant) {
3794 // hand off to the non-spec-constant path
3795 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3796 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003797 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003798 nextConst, false);
3799 }
3800
3801 // We now know we have a specialization constant to build
3802
qining4f4bb812016-04-03 23:55:17 -04003803 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3804 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3805 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3806 std::vector<spv::Id> dimConstId;
3807 for (int dim = 0; dim < 3; ++dim) {
3808 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3809 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3810 if (specConst)
3811 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3812 }
3813 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3814 }
3815
3816 // An AST node labelled as specialization constant should be a symbol node.
3817 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3818 if (auto* sn = node.getAsSymbolNode()) {
3819 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04003820 // Traverse the constant constructor sub tree like generating normal run-time instructions.
3821 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
3822 // will set the builder into spec constant op instruction generating mode.
3823 sub_tree->traverse(this);
3824 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04003825 } else if (auto* const_union_array = &sn->getConstArray()){
3826 int nextConst = 0;
3827 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003828 }
3829 }
qining4f4bb812016-04-03 23:55:17 -04003830
3831 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3832 // constant sub tree as initializer.
3833 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3834 exit(1);
3835 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003836}
3837
John Kessenich140f3df2015-06-26 16:58:36 -06003838// Use 'consts' as the flattened glslang source of scalar constants to recursively
3839// build the aggregate SPIR-V constant.
3840//
3841// If there are not enough elements present in 'consts', 0 will be substituted;
3842// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3843//
qining08408382016-03-21 09:51:37 -04003844spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003845{
3846 // vector of constants for SPIR-V
3847 std::vector<spv::Id> spvConsts;
3848
3849 // Type is used for struct and array constants
3850 spv::Id typeId = convertGlslangToSpvType(glslangType);
3851
3852 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003853 glslang::TType elementType(glslangType, 0);
3854 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003855 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003856 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003857 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003858 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003859 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003860 } else if (glslangType.getStruct()) {
3861 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3862 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003863 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003864 } else if (glslangType.isVector()) {
3865 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3866 bool zero = nextConst >= consts.size();
3867 switch (glslangType.getBasicType()) {
3868 case glslang::EbtInt:
3869 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3870 break;
3871 case glslang::EbtUint:
3872 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3873 break;
3874 case glslang::EbtFloat:
3875 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3876 break;
3877 case glslang::EbtDouble:
3878 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3879 break;
3880 case glslang::EbtBool:
3881 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3882 break;
3883 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003884 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003885 break;
3886 }
3887 ++nextConst;
3888 }
3889 } else {
3890 // we have a non-aggregate (scalar) constant
3891 bool zero = nextConst >= consts.size();
3892 spv::Id scalar = 0;
3893 switch (glslangType.getBasicType()) {
3894 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003895 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 break;
3897 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003898 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003899 break;
3900 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003901 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003902 break;
3903 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003904 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003905 break;
3906 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003907 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003908 break;
3909 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003910 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003911 break;
3912 }
3913 ++nextConst;
3914 return scalar;
3915 }
3916
3917 return builder.makeCompositeConstant(typeId, spvConsts);
3918}
3919
John Kessenich7c1aa102015-10-15 13:29:11 -06003920// Return true if the node is a constant or symbol whose reading has no
3921// non-trivial observable cost or effect.
3922bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3923{
3924 // don't know what this is
3925 if (node == nullptr)
3926 return false;
3927
3928 // a constant is safe
3929 if (node->getAsConstantUnion() != nullptr)
3930 return true;
3931
3932 // not a symbol means non-trivial
3933 if (node->getAsSymbolNode() == nullptr)
3934 return false;
3935
3936 // a symbol, depends on what's being read
3937 switch (node->getType().getQualifier().storage) {
3938 case glslang::EvqTemporary:
3939 case glslang::EvqGlobal:
3940 case glslang::EvqIn:
3941 case glslang::EvqInOut:
3942 case glslang::EvqConst:
3943 case glslang::EvqConstReadOnly:
3944 case glslang::EvqUniform:
3945 return true;
3946 default:
3947 return false;
3948 }
3949}
3950
3951// A node is trivial if it is a single operation with no side effects.
3952// Error on the side of saying non-trivial.
3953// Return true if trivial.
3954bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3955{
3956 if (node == nullptr)
3957 return false;
3958
3959 // symbols and constants are trivial
3960 if (isTrivialLeaf(node))
3961 return true;
3962
3963 // otherwise, it needs to be a simple operation or one or two leaf nodes
3964
3965 // not a simple operation
3966 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3967 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3968 if (binaryNode == nullptr && unaryNode == nullptr)
3969 return false;
3970
3971 // not on leaf nodes
3972 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3973 return false;
3974
3975 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3976 return false;
3977 }
3978
3979 switch (node->getAsOperator()->getOp()) {
3980 case glslang::EOpLogicalNot:
3981 case glslang::EOpConvIntToBool:
3982 case glslang::EOpConvUintToBool:
3983 case glslang::EOpConvFloatToBool:
3984 case glslang::EOpConvDoubleToBool:
3985 case glslang::EOpEqual:
3986 case glslang::EOpNotEqual:
3987 case glslang::EOpLessThan:
3988 case glslang::EOpGreaterThan:
3989 case glslang::EOpLessThanEqual:
3990 case glslang::EOpGreaterThanEqual:
3991 case glslang::EOpIndexDirect:
3992 case glslang::EOpIndexDirectStruct:
3993 case glslang::EOpLogicalXor:
3994 case glslang::EOpAny:
3995 case glslang::EOpAll:
3996 return true;
3997 default:
3998 return false;
3999 }
4000}
4001
4002// Emit short-circuiting code, where 'right' is never evaluated unless
4003// the left side is true (for &&) or false (for ||).
4004spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4005{
4006 spv::Id boolTypeId = builder.makeBoolType();
4007
4008 // emit left operand
4009 builder.clearAccessChain();
4010 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004011 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004012
4013 // Operands to accumulate OpPhi operands
4014 std::vector<spv::Id> phiOperands;
4015 // accumulate left operand's phi information
4016 phiOperands.push_back(leftId);
4017 phiOperands.push_back(builder.getBuildPoint()->getId());
4018
4019 // Make the two kinds of operation symmetric with a "!"
4020 // || => emit "if (! left) result = right"
4021 // && => emit "if ( left) result = right"
4022 //
4023 // TODO: this runtime "not" for || could be avoided by adding functionality
4024 // to 'builder' to have an "else" without an "then"
4025 if (op == glslang::EOpLogicalOr)
4026 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4027
4028 // make an "if" based on the left value
4029 spv::Builder::If ifBuilder(leftId, builder);
4030
4031 // emit right operand as the "then" part of the "if"
4032 builder.clearAccessChain();
4033 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004034 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004035
4036 // accumulate left operand's phi information
4037 phiOperands.push_back(rightId);
4038 phiOperands.push_back(builder.getBuildPoint()->getId());
4039
4040 // finish the "if"
4041 ifBuilder.makeEndIf();
4042
4043 // phi together the two results
4044 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4045}
4046
John Kessenich140f3df2015-06-26 16:58:36 -06004047}; // end anonymous namespace
4048
4049namespace glslang {
4050
John Kessenich68d78fd2015-07-12 19:28:10 -06004051void GetSpirvVersion(std::string& version)
4052{
John Kessenich9e55f632015-07-15 10:03:39 -06004053 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004054 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004055 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004056 version = buf;
4057}
4058
John Kessenich140f3df2015-06-26 16:58:36 -06004059// Write SPIR-V out to a binary file
4060void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4061{
4062 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004063 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004064 for (int i = 0; i < (int)spirv.size(); ++i) {
4065 unsigned int word = spirv[i];
4066 out.write((const char*)&word, 4);
4067 }
4068 out.close();
4069}
4070
4071//
4072// Set up the glslang traversal
4073//
4074void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4075{
4076 TIntermNode* root = intermediate.getTreeRoot();
4077
4078 if (root == 0)
4079 return;
4080
4081 glslang::GetThreadPoolAllocator().push();
4082
4083 TGlslangToSpvTraverser it(&intermediate);
4084
4085 root->traverse(&it);
4086
4087 it.dumpSpv(spirv);
4088
4089 glslang::GetThreadPoolAllocator().pop();
4090}
4091
4092}; // end namespace glslang