blob: 7aa62fbd12c1abe86f379d77c1c5578bc2982608 [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
John Kessenich140f3df2015-06-26 16:58:36 -060055#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040056#include <list>
57#include <map>
58#include <stack>
59#include <string>
60#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060061
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:
Lei Zhang17535f72016-05-04 15:55:59 -040097 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060098 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 Kessenich91cef522016-05-05 16:45:40 -0600145 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600146 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 -0600147 spv::Id createNoArgOperation(glslang::TOperator op);
148 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
149 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700150 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700152 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400153 spv::Id createSpvConstant(const glslang::TIntermTyped&);
154 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600155 bool isTrivialLeaf(const glslang::TIntermTyped* node);
156 bool isTrivial(const glslang::TIntermTyped* node);
157 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600158
159 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700160 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600161 int sequenceDepth;
162
Lei Zhang17535f72016-05-04 15:55:59 -0400163 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400164
John Kessenich140f3df2015-06-26 16:58:36 -0600165 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
166 spv::Builder builder;
167 bool inMain;
168 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700169 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 -0700170 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600171 const glslang::TIntermediate* glslangIntermediate;
172 spv::Id stdBuiltins;
173
John Kessenich2f273362015-07-18 22:34:27 -0600174 std::unordered_map<int, spv::Id> symbolValues;
175 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
176 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700177 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600178 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 -0600179 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600180};
181
182//
183// Helper functions for translating glslang representations to SPIR-V enumerants.
184//
185
186// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700187spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600188{
John Kessenich66e2faf2016-03-12 18:34:36 -0700189 switch (source) {
190 case glslang::EShSourceGlsl:
191 switch (profile) {
192 case ENoProfile:
193 case ECoreProfile:
194 case ECompatibilityProfile:
195 return spv::SourceLanguageGLSL;
196 case EEsProfile:
197 return spv::SourceLanguageESSL;
198 default:
199 return spv::SourceLanguageUnknown;
200 }
201 case glslang::EShSourceHlsl:
202 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 default:
204 return spv::SourceLanguageUnknown;
205 }
206}
207
208// Translate glslang language (stage) to SPIR-V execution model.
209spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
210{
211 switch (stage) {
212 case EShLangVertex: return spv::ExecutionModelVertex;
213 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
214 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
215 case EShLangGeometry: return spv::ExecutionModelGeometry;
216 case EShLangFragment: return spv::ExecutionModelFragment;
217 case EShLangCompute: return spv::ExecutionModelGLCompute;
218 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700219 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600220 return spv::ExecutionModelFragment;
221 }
222}
223
224// Translate glslang type to SPIR-V storage class.
225spv::StorageClass TranslateStorageClass(const glslang::TType& type)
226{
227 if (type.getQualifier().isPipeInput())
228 return spv::StorageClassInput;
229 else if (type.getQualifier().isPipeOutput())
230 return spv::StorageClassOutput;
231 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700232 if (type.getQualifier().layoutPushConstant)
233 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 if (type.getBasicType() == glslang::EbtBlock)
235 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800236 else if (type.getBasicType() == glslang::EbtAtomicUint)
237 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 else
239 return spv::StorageClassUniformConstant;
240 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
241 } else {
242 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700243 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
244 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600245 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
246 case glslang::EvqTemporary: return spv::StorageClassFunction;
247 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700248 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600249 return spv::StorageClassFunction;
250 }
251 }
252}
253
254// Translate glslang sampler type to SPIR-V dimensionality.
255spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
256{
257 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700258 case glslang::Esd1D: return spv::Dim1D;
259 case glslang::Esd2D: return spv::Dim2D;
260 case glslang::Esd3D: return spv::Dim3D;
261 case glslang::EsdCube: return spv::DimCube;
262 case glslang::EsdRect: return spv::DimRect;
263 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700264 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700266 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600267 return spv::Dim2D;
268 }
269}
270
271// Translate glslang type to SPIR-V precision decorations.
272spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
273{
274 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700275 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600276 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600277 default:
278 return spv::NoPrecision;
279 }
280}
281
282// Translate glslang type to SPIR-V block decorations.
283spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
284{
285 if (type.getBasicType() == glslang::EbtBlock) {
286 switch (type.getQualifier().storage) {
287 case glslang::EvqUniform: return spv::DecorationBlock;
288 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
289 case glslang::EvqVaryingIn: return spv::DecorationBlock;
290 case glslang::EvqVaryingOut: return spv::DecorationBlock;
291 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700292 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600293 break;
294 }
295 }
296
297 return (spv::Decoration)spv::BadValue;
298}
299
Rex Xu1da878f2016-02-21 20:59:01 +0800300// Translate glslang type to SPIR-V memory decorations.
301void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
302{
303 if (qualifier.coherent)
304 memory.push_back(spv::DecorationCoherent);
305 if (qualifier.volatil)
306 memory.push_back(spv::DecorationVolatile);
307 if (qualifier.restrict)
308 memory.push_back(spv::DecorationRestrict);
309 if (qualifier.readonly)
310 memory.push_back(spv::DecorationNonWritable);
311 if (qualifier.writeonly)
312 memory.push_back(spv::DecorationNonReadable);
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700316spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600317{
318 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700319 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600320 case glslang::ElmRowMajor:
321 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600323 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700324 default:
325 // opaque layouts don't need a majorness
326 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600327 }
328 } else {
329 switch (type.getBasicType()) {
330 default:
331 return (spv::Decoration)spv::BadValue;
332 break;
333 case glslang::EbtBlock:
334 switch (type.getQualifier().storage) {
335 case glslang::EvqUniform:
336 case glslang::EvqBuffer:
337 switch (type.getQualifier().layoutPacking) {
338 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600339 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
340 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600341 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 case glslang::EvqVaryingIn:
344 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 return (spv::Decoration)spv::BadValue;
347 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600349 return (spv::Decoration)spv::BadValue;
350 }
351 }
352 }
353}
354
355// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700356// Returns spv::Decoration(spv::BadValue) when no decoration
357// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700358spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600359{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700360 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700361 // Smooth decoration doesn't exist in SPIR-V 1.0
362 return (spv::Decoration)spv::BadValue;
363 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700364 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700370 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600371 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700372 else if (qualifier.sample) {
373 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600374 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700375 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600376 return (spv::Decoration)spv::BadValue;
377}
378
John Kessenich92187592016-02-01 13:45:25 -0700379// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600381{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700382 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600383 return spv::DecorationInvariant;
384 else
385 return (spv::Decoration)spv::BadValue;
386}
387
388// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700389spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
391 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700392 case glslang::EbvPointSize:
393 switch (glslangIntermediate->getStage()) {
394 case EShLangGeometry:
395 builder.addCapability(spv::CapabilityGeometryPointSize);
396 break;
397 case EShLangTessControl:
398 case EShLangTessEvaluation:
399 builder.addCapability(spv::CapabilityTessellationPointSize);
400 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100401 default:
402 break;
John Kessenich92187592016-02-01 13:45:25 -0700403 }
404 return spv::BuiltInPointSize;
405
406 case glslang::EbvClipDistance:
407 builder.addCapability(spv::CapabilityClipDistance);
408 return spv::BuiltInClipDistance;
409
410 case glslang::EbvCullDistance:
411 builder.addCapability(spv::CapabilityCullDistance);
412 return spv::BuiltInCullDistance;
413
414 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500415 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700416 return spv::BuiltInViewportIndex;
417
John Kessenich5e801132016-02-15 11:09:46 -0700418 case glslang::EbvSampleId:
419 builder.addCapability(spv::CapabilitySampleRateShading);
420 return spv::BuiltInSampleId;
421
422 case glslang::EbvSamplePosition:
423 builder.addCapability(spv::CapabilitySampleRateShading);
424 return spv::BuiltInSamplePosition;
425
426 case glslang::EbvSampleMask:
427 builder.addCapability(spv::CapabilitySampleRateShading);
428 return spv::BuiltInSampleMask;
429
John Kessenich140f3df2015-06-26 16:58:36 -0600430 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 case glslang::EbvVertexId: return spv::BuiltInVertexId;
432 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700433 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
434 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600435 case glslang::EbvBaseVertex:
436 case glslang::EbvBaseInstance:
437 case glslang::EbvDrawId:
438 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600439 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600440 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600441 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
442 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
443 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600444 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
445 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
446 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
447 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
448 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
449 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
450 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600451 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
452 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
453 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
454 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
455 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
456 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
457 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
458 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800459 case glslang::EbvSubGroupSize:
460 case glslang::EbvSubGroupInvocation:
461 case glslang::EbvSubGroupEqMask:
462 case glslang::EbvSubGroupGeMask:
463 case glslang::EbvSubGroupGtMask:
464 case glslang::EbvSubGroupLeMask:
465 case glslang::EbvSubGroupLtMask:
466 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600467 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800468 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600469 default: return (spv::BuiltIn)spv::BadValue;
470 }
471}
472
Rex Xufc618912015-09-09 16:42:49 +0800473// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700474spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800475{
476 assert(type.getBasicType() == glslang::EbtSampler);
477
John Kessenich5d0fa972016-02-15 11:57:00 -0700478 // Check for capabilities
479 switch (type.getQualifier().layoutFormat) {
480 case glslang::ElfRg32f:
481 case glslang::ElfRg16f:
482 case glslang::ElfR11fG11fB10f:
483 case glslang::ElfR16f:
484 case glslang::ElfRgba16:
485 case glslang::ElfRgb10A2:
486 case glslang::ElfRg16:
487 case glslang::ElfRg8:
488 case glslang::ElfR16:
489 case glslang::ElfR8:
490 case glslang::ElfRgba16Snorm:
491 case glslang::ElfRg16Snorm:
492 case glslang::ElfRg8Snorm:
493 case glslang::ElfR16Snorm:
494 case glslang::ElfR8Snorm:
495
496 case glslang::ElfRg32i:
497 case glslang::ElfRg16i:
498 case glslang::ElfRg8i:
499 case glslang::ElfR16i:
500 case glslang::ElfR8i:
501
502 case glslang::ElfRgb10a2ui:
503 case glslang::ElfRg32ui:
504 case glslang::ElfRg16ui:
505 case glslang::ElfRg8ui:
506 case glslang::ElfR16ui:
507 case glslang::ElfR8ui:
508 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
509 break;
510
511 default:
512 break;
513 }
514
515 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800516 switch (type.getQualifier().layoutFormat) {
517 case glslang::ElfNone: return spv::ImageFormatUnknown;
518 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
519 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
520 case glslang::ElfR32f: return spv::ImageFormatR32f;
521 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
522 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
523 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
524 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
525 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
526 case glslang::ElfR16f: return spv::ImageFormatR16f;
527 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
528 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
529 case glslang::ElfRg16: return spv::ImageFormatRg16;
530 case glslang::ElfRg8: return spv::ImageFormatRg8;
531 case glslang::ElfR16: return spv::ImageFormatR16;
532 case glslang::ElfR8: return spv::ImageFormatR8;
533 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
534 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
535 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
536 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
537 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
538 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
539 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
540 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
541 case glslang::ElfR32i: return spv::ImageFormatR32i;
542 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
543 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
544 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
545 case glslang::ElfR16i: return spv::ImageFormatR16i;
546 case glslang::ElfR8i: return spv::ImageFormatR8i;
547 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
548 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
549 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
550 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
551 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
552 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
553 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
554 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
555 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
556 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
557 default: return (spv::ImageFormat)spv::BadValue;
558 }
559}
560
John Kessenich6c292d32016-02-15 20:58:50 -0700561// Return whether or not the given type is something that should be tied to a
562// descriptor set.
563bool IsDescriptorResource(const glslang::TType& type)
564{
John Kessenichf7497e22016-03-08 21:36:22 -0700565 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700566 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700567 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700568
569 // non block...
570 // basically samplerXXX/subpass/sampler/texture are all included
571 // if they are the global-scope-class, not the function parameter
572 // (or local, if they ever exist) class.
573 if (type.getBasicType() == glslang::EbtSampler)
574 return type.getQualifier().isUniformOrBuffer();
575
576 // None of the above.
577 return false;
578}
579
John Kesseniche0b6cad2015-12-24 10:30:13 -0700580void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
581{
582 if (child.layoutMatrix == glslang::ElmNone)
583 child.layoutMatrix = parent.layoutMatrix;
584
585 if (parent.invariant)
586 child.invariant = true;
587 if (parent.nopersp)
588 child.nopersp = true;
589 if (parent.flat)
590 child.flat = true;
591 if (parent.centroid)
592 child.centroid = true;
593 if (parent.patch)
594 child.patch = true;
595 if (parent.sample)
596 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800597 if (parent.coherent)
598 child.coherent = true;
599 if (parent.volatil)
600 child.volatil = true;
601 if (parent.restrict)
602 child.restrict = true;
603 if (parent.readonly)
604 child.readonly = true;
605 if (parent.writeonly)
606 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700607}
608
609bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
610{
John Kessenich7b9fa252016-01-21 18:56:57 -0700611 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700612 // - struct members can inherit from a struct declaration
613 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
614 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700615 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700616}
617
John Kessenich140f3df2015-06-26 16:58:36 -0600618//
619// Implement the TGlslangToSpvTraverser class.
620//
621
Lei Zhang17535f72016-05-04 15:55:59 -0400622TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
623 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
624 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600625 inMain(false), mainTerminated(false), linkageOnly(false),
626 glslangIntermediate(glslangIntermediate)
627{
628 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
629
630 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700631 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600632 stdBuiltins = builder.import("GLSL.std.450");
633 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700634 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
635 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600636
637 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600638 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
639 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600640 builder.addSourceExtension(it->c_str());
641
642 // Add the top-level modes for this shader.
643
John Kessenich92187592016-02-01 13:45:25 -0700644 if (glslangIntermediate->getXfbMode()) {
645 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600646 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700647 }
John Kessenich140f3df2015-06-26 16:58:36 -0600648
649 unsigned int mode;
650 switch (glslangIntermediate->getStage()) {
651 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600652 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 break;
654
655 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600656 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600657 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
658 break;
659
660 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600661 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600662 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700663 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
664 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
665 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600666 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600667 }
668 if (mode != spv::BadValue)
669 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
670
John Kesseniche6903322015-10-13 16:29:02 -0600671 switch (glslangIntermediate->getVertexSpacing()) {
672 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
673 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
674 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
675 default: mode = spv::BadValue; break;
676 }
677 if (mode != spv::BadValue)
678 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
679
680 switch (glslangIntermediate->getVertexOrder()) {
681 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
682 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
683 default: mode = spv::BadValue; break;
684 }
685 if (mode != spv::BadValue)
686 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
687
688 if (glslangIntermediate->getPointMode())
689 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600690 break;
691
692 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600693 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600694 switch (glslangIntermediate->getInputPrimitive()) {
695 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
696 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
697 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700698 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600699 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
700 default: mode = spv::BadValue; break;
701 }
702 if (mode != spv::BadValue)
703 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
706
707 switch (glslangIntermediate->getOutputPrimitive()) {
708 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
709 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
710 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
711 default: mode = spv::BadValue; break;
712 }
713 if (mode != spv::BadValue)
714 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
715 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
716 break;
717
718 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600719 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600720 if (glslangIntermediate->getPixelCenterInteger())
721 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600722
John Kessenich140f3df2015-06-26 16:58:36 -0600723 if (glslangIntermediate->getOriginUpperLeft())
724 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600725 else
726 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600727
728 if (glslangIntermediate->getEarlyFragmentTests())
729 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
730
731 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600732 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
733 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
734 default: mode = spv::BadValue; break;
735 }
736 if (mode != spv::BadValue)
737 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
738
739 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
740 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600741 break;
742
743 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600744 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600745 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
746 glslangIntermediate->getLocalSize(1),
747 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600748 break;
749
750 default:
751 break;
752 }
753
754}
755
John Kessenich7ba63412015-12-20 17:37:07 -0700756// Finish everything and dump
757void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
758{
759 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100760 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
761 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700762
qiningda397332016-03-09 19:54:03 -0500763 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700764 builder.dump(out);
765}
766
John Kessenich140f3df2015-06-26 16:58:36 -0600767TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
768{
769 if (! mainTerminated) {
770 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
771 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600772 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600773 }
774}
775
776//
777// Implement the traversal functions.
778//
779// Return true from interior nodes to have the external traversal
780// continue on to children. Return false if children were
781// already processed.
782//
783
784//
785// Symbols can turn into
786// - uniform/input reads
787// - output writes
788// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
789// - something simple that degenerates into the last bullet
790//
791void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
792{
qining75d1d802016-04-06 14:42:01 -0400793 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
794 if (symbol->getType().getQualifier().isSpecConstant())
795 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
796
John Kessenich140f3df2015-06-26 16:58:36 -0600797 // getSymbolId() will set up all the IO decorations on the first call.
798 // Formal function parameters were mapped during makeFunctions().
799 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700800
801 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
802 if (builder.isPointer(id)) {
803 spv::StorageClass sc = builder.getStorageClass(id);
804 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
805 iOSet.insert(id);
806 }
807
808 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700809 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600810 // Prepare to generate code for the access
811
812 // L-value chains will be computed left to right. We're on the symbol now,
813 // which is the left-most part of the access chain, so now is "clear" time,
814 // followed by setting the base.
815 builder.clearAccessChain();
816
817 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700818 // except for
819 // A) "const in" arguments to a function, which are an intermediate object.
820 // See comments in handleUserFunctionCall().
821 // B) Specialization constants (normal constant don't even come in as a variable),
822 // These are also pure R-values.
823 glslang::TQualifier qualifier = symbol->getQualifier();
824 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
825 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600826 builder.setAccessChainRValue(id);
827 else
828 builder.setAccessChainLValue(id);
829 }
830}
831
832bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
833{
qining40887662016-04-03 22:20:42 -0400834 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
835 if (node->getType().getQualifier().isSpecConstant())
836 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
837
John Kessenich140f3df2015-06-26 16:58:36 -0600838 // First, handle special cases
839 switch (node->getOp()) {
840 case glslang::EOpAssign:
841 case glslang::EOpAddAssign:
842 case glslang::EOpSubAssign:
843 case glslang::EOpMulAssign:
844 case glslang::EOpVectorTimesMatrixAssign:
845 case glslang::EOpVectorTimesScalarAssign:
846 case glslang::EOpMatrixTimesScalarAssign:
847 case glslang::EOpMatrixTimesMatrixAssign:
848 case glslang::EOpDivAssign:
849 case glslang::EOpModAssign:
850 case glslang::EOpAndAssign:
851 case glslang::EOpInclusiveOrAssign:
852 case glslang::EOpExclusiveOrAssign:
853 case glslang::EOpLeftShiftAssign:
854 case glslang::EOpRightShiftAssign:
855 // A bin-op assign "a += b" means the same thing as "a = a + b"
856 // where a is evaluated before b. For a simple assignment, GLSL
857 // says to evaluate the left before the right. So, always, left
858 // node then right node.
859 {
860 // get the left l-value, save it away
861 builder.clearAccessChain();
862 node->getLeft()->traverse(this);
863 spv::Builder::AccessChain lValue = builder.getAccessChain();
864
865 // evaluate the right
866 builder.clearAccessChain();
867 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700868 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600869
870 if (node->getOp() != glslang::EOpAssign) {
871 // the left is also an r-value
872 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700873 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600874
875 // do the operation
876 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
877 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
878 node->getType().getBasicType());
879
880 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700881 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600882 }
883
884 // store the result
885 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800886 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600887
888 // assignments are expressions having an rValue after they are evaluated...
889 builder.clearAccessChain();
890 builder.setAccessChainRValue(rValue);
891 }
892 return false;
893 case glslang::EOpIndexDirect:
894 case glslang::EOpIndexDirectStruct:
895 {
896 // Get the left part of the access chain.
897 node->getLeft()->traverse(this);
898
899 // Add the next element in the chain
900
John Kessenich55e7d112015-11-15 21:33:39 -0700901 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600902 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
903 // This may be, e.g., an anonymous block-member selection, which generally need
904 // index remapping due to hidden members in anonymous blocks.
905 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700906 assert(remapper.size() > 0);
907 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600908 }
909
910 if (! node->getLeft()->getType().isArray() &&
911 node->getLeft()->getType().isVector() &&
912 node->getOp() == glslang::EOpIndexDirect) {
913 // This is essentially a hard-coded vector swizzle of size 1,
914 // so short circuit the access-chain stuff with a swizzle.
915 std::vector<unsigned> swizzle;
916 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600917 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600918 } else {
919 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600920 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600921 }
922 }
923 return false;
924 case glslang::EOpIndexIndirect:
925 {
926 // Structure or array or vector indirection.
927 // Will use native SPIR-V access-chain for struct and array indirection;
928 // matrices are arrays of vectors, so will also work for a matrix.
929 // Will use the access chain's 'component' for variable index into a vector.
930
931 // This adapter is building access chains left to right.
932 // Set up the access chain to the left.
933 node->getLeft()->traverse(this);
934
935 // save it so that computing the right side doesn't trash it
936 spv::Builder::AccessChain partial = builder.getAccessChain();
937
938 // compute the next index in the chain
939 builder.clearAccessChain();
940 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700941 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600942
943 // restore the saved access chain
944 builder.setAccessChain(partial);
945
946 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600947 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600948 else
John Kessenichfa668da2015-09-13 14:46:30 -0600949 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600950 }
951 return false;
952 case glslang::EOpVectorSwizzle:
953 {
954 node->getLeft()->traverse(this);
955 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
956 std::vector<unsigned> swizzle;
957 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
958 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600959 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600960 }
961 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600962 case glslang::EOpLogicalOr:
963 case glslang::EOpLogicalAnd:
964 {
965
966 // These may require short circuiting, but can sometimes be done as straight
967 // binary operations. The right operand must be short circuited if it has
968 // side effects, and should probably be if it is complex.
969 if (isTrivial(node->getRight()->getAsTyped()))
970 break; // handle below as a normal binary operation
971 // otherwise, we need to do dynamic short circuiting on the right operand
972 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
973 builder.clearAccessChain();
974 builder.setAccessChainRValue(result);
975 }
976 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600977 default:
978 break;
979 }
980
981 // Assume generic binary op...
982
John Kessenich32cfd492016-02-02 12:37:46 -0700983 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600984 builder.clearAccessChain();
985 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700986 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600987
John Kessenich32cfd492016-02-02 12:37:46 -0700988 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600989 builder.clearAccessChain();
990 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700991 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600992
John Kessenich32cfd492016-02-02 12:37:46 -0700993 // get result
994 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
995 convertGlslangToSpvType(node->getType()), left, right,
996 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600997
John Kessenich50e57562015-12-21 21:21:11 -0700998 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600999 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001000 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001001 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001002 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001003 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001004 return false;
1005 }
John Kessenich140f3df2015-06-26 16:58:36 -06001006}
1007
1008bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1009{
qining40887662016-04-03 22:20:42 -04001010 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1011 if (node->getType().getQualifier().isSpecConstant())
1012 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1013
John Kessenichfc51d282015-08-19 13:34:18 -06001014 spv::Id result = spv::NoResult;
1015
1016 // try texturing first
1017 result = createImageTextureFunctionCall(node);
1018 if (result != spv::NoResult) {
1019 builder.clearAccessChain();
1020 builder.setAccessChainRValue(result);
1021
1022 return false; // done with this node
1023 }
1024
1025 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001026
1027 if (node->getOp() == glslang::EOpArrayLength) {
1028 // Quite special; won't want to evaluate the operand.
1029
1030 // Normal .length() would have been constant folded by the front-end.
1031 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001032 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001033 assert(node->getOperand()->getType().isRuntimeSizedArray());
1034 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1035 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001036 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1037 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001038
1039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(length);
1041
1042 return false;
1043 }
1044
John Kessenichfc51d282015-08-19 13:34:18 -06001045 // Start by evaluating the operand
1046
John Kessenich140f3df2015-06-26 16:58:36 -06001047 builder.clearAccessChain();
1048 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001049
Rex Xufc618912015-09-09 16:42:49 +08001050 spv::Id operand = spv::NoResult;
1051
1052 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1053 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001054 node->getOp() == glslang::EOpAtomicCounter ||
1055 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001056 operand = builder.accessChainGetLValue(); // Special case l-value operands
1057 else
John Kessenich32cfd492016-02-02 12:37:46 -07001058 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001059
1060 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1061
1062 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001063 if (! result)
1064 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001065
1066 // if not, then possibly an operation
1067 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001068 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001069
1070 if (result) {
1071 builder.clearAccessChain();
1072 builder.setAccessChainRValue(result);
1073
1074 return false; // done with this node
1075 }
1076
1077 // it must be a special case, check...
1078 switch (node->getOp()) {
1079 case glslang::EOpPostIncrement:
1080 case glslang::EOpPostDecrement:
1081 case glslang::EOpPreIncrement:
1082 case glslang::EOpPreDecrement:
1083 {
1084 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001085 spv::Id one = 0;
1086 if (node->getBasicType() == glslang::EbtFloat)
1087 one = builder.makeFloatConstant(1.0F);
1088 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1089 one = builder.makeInt64Constant(1);
1090 else
1091 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001092 glslang::TOperator op;
1093 if (node->getOp() == glslang::EOpPreIncrement ||
1094 node->getOp() == glslang::EOpPostIncrement)
1095 op = glslang::EOpAdd;
1096 else
1097 op = glslang::EOpSub;
1098
1099 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001100 convertGlslangToSpvType(node->getType()), operand, one,
1101 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001102 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001103
1104 // The result of operation is always stored, but conditionally the
1105 // consumed result. The consumed result is always an r-value.
1106 builder.accessChainStore(result);
1107 builder.clearAccessChain();
1108 if (node->getOp() == glslang::EOpPreIncrement ||
1109 node->getOp() == glslang::EOpPreDecrement)
1110 builder.setAccessChainRValue(result);
1111 else
1112 builder.setAccessChainRValue(operand);
1113 }
1114
1115 return false;
1116
1117 case glslang::EOpEmitStreamVertex:
1118 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1119 return false;
1120 case glslang::EOpEndStreamPrimitive:
1121 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1122 return false;
1123
1124 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001125 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001126 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001127 }
John Kessenich140f3df2015-06-26 16:58:36 -06001128}
1129
1130bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1131{
qining27e04a02016-04-14 16:40:20 -04001132 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1133 if (node->getType().getQualifier().isSpecConstant())
1134 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1135
John Kessenichfc51d282015-08-19 13:34:18 -06001136 spv::Id result = spv::NoResult;
1137
1138 // try texturing
1139 result = createImageTextureFunctionCall(node);
1140 if (result != spv::NoResult) {
1141 builder.clearAccessChain();
1142 builder.setAccessChainRValue(result);
1143
1144 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001145 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001146 // "imageStore" is a special case, which has no result
1147 return false;
1148 }
John Kessenichfc51d282015-08-19 13:34:18 -06001149
John Kessenich140f3df2015-06-26 16:58:36 -06001150 glslang::TOperator binOp = glslang::EOpNull;
1151 bool reduceComparison = true;
1152 bool isMatrix = false;
1153 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001154 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 assert(node->getOp());
1157
1158 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1159
1160 switch (node->getOp()) {
1161 case glslang::EOpSequence:
1162 {
1163 if (preVisit)
1164 ++sequenceDepth;
1165 else
1166 --sequenceDepth;
1167
1168 if (sequenceDepth == 1) {
1169 // If this is the parent node of all the functions, we want to see them
1170 // early, so all call points have actual SPIR-V functions to reference.
1171 // In all cases, still let the traverser visit the children for us.
1172 makeFunctions(node->getAsAggregate()->getSequence());
1173
1174 // Also, we want all globals initializers to go into the entry of main(), before
1175 // anything else gets there, so visit out of order, doing them all now.
1176 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1177
1178 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1179 // so do them manually.
1180 visitFunctions(node->getAsAggregate()->getSequence());
1181
1182 return false;
1183 }
1184
1185 return true;
1186 }
1187 case glslang::EOpLinkerObjects:
1188 {
1189 if (visit == glslang::EvPreVisit)
1190 linkageOnly = true;
1191 else
1192 linkageOnly = false;
1193
1194 return true;
1195 }
1196 case glslang::EOpComma:
1197 {
1198 // processing from left to right naturally leaves the right-most
1199 // lying around in the access chain
1200 glslang::TIntermSequence& glslangOperands = node->getSequence();
1201 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1202 glslangOperands[i]->traverse(this);
1203
1204 return false;
1205 }
1206 case glslang::EOpFunction:
1207 if (visit == glslang::EvPreVisit) {
1208 if (isShaderEntrypoint(node)) {
1209 inMain = true;
1210 builder.setBuildPoint(shaderEntry->getLastBlock());
1211 } else {
1212 handleFunctionEntry(node);
1213 }
1214 } else {
1215 if (inMain)
1216 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001217 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001218 inMain = false;
1219 }
1220
1221 return true;
1222 case glslang::EOpParameters:
1223 // Parameters will have been consumed by EOpFunction processing, but not
1224 // the body, so we still visited the function node's children, making this
1225 // child redundant.
1226 return false;
1227 case glslang::EOpFunctionCall:
1228 {
1229 if (node->isUserDefined())
1230 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001231 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1232 if (result) {
1233 builder.clearAccessChain();
1234 builder.setAccessChainRValue(result);
1235 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001236 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001237
1238 return false;
1239 }
1240 case glslang::EOpConstructMat2x2:
1241 case glslang::EOpConstructMat2x3:
1242 case glslang::EOpConstructMat2x4:
1243 case glslang::EOpConstructMat3x2:
1244 case glslang::EOpConstructMat3x3:
1245 case glslang::EOpConstructMat3x4:
1246 case glslang::EOpConstructMat4x2:
1247 case glslang::EOpConstructMat4x3:
1248 case glslang::EOpConstructMat4x4:
1249 case glslang::EOpConstructDMat2x2:
1250 case glslang::EOpConstructDMat2x3:
1251 case glslang::EOpConstructDMat2x4:
1252 case glslang::EOpConstructDMat3x2:
1253 case glslang::EOpConstructDMat3x3:
1254 case glslang::EOpConstructDMat3x4:
1255 case glslang::EOpConstructDMat4x2:
1256 case glslang::EOpConstructDMat4x3:
1257 case glslang::EOpConstructDMat4x4:
1258 isMatrix = true;
1259 // fall through
1260 case glslang::EOpConstructFloat:
1261 case glslang::EOpConstructVec2:
1262 case glslang::EOpConstructVec3:
1263 case glslang::EOpConstructVec4:
1264 case glslang::EOpConstructDouble:
1265 case glslang::EOpConstructDVec2:
1266 case glslang::EOpConstructDVec3:
1267 case glslang::EOpConstructDVec4:
1268 case glslang::EOpConstructBool:
1269 case glslang::EOpConstructBVec2:
1270 case glslang::EOpConstructBVec3:
1271 case glslang::EOpConstructBVec4:
1272 case glslang::EOpConstructInt:
1273 case glslang::EOpConstructIVec2:
1274 case glslang::EOpConstructIVec3:
1275 case glslang::EOpConstructIVec4:
1276 case glslang::EOpConstructUint:
1277 case glslang::EOpConstructUVec2:
1278 case glslang::EOpConstructUVec3:
1279 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001280 case glslang::EOpConstructInt64:
1281 case glslang::EOpConstructI64Vec2:
1282 case glslang::EOpConstructI64Vec3:
1283 case glslang::EOpConstructI64Vec4:
1284 case glslang::EOpConstructUint64:
1285 case glslang::EOpConstructU64Vec2:
1286 case glslang::EOpConstructU64Vec3:
1287 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001288 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001289 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001290 {
1291 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001292 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001293 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1294 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001295 if (node->getOp() == glslang::EOpConstructTextureSampler)
1296 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1297 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001298 std::vector<spv::Id> constituents;
1299 for (int c = 0; c < (int)arguments.size(); ++c)
1300 constituents.push_back(arguments[c]);
1301 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001302 } else if (isMatrix)
1303 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1304 else
1305 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001306
1307 builder.clearAccessChain();
1308 builder.setAccessChainRValue(constructed);
1309
1310 return false;
1311 }
1312
1313 // These six are component-wise compares with component-wise results.
1314 // Forward on to createBinaryOperation(), requesting a vector result.
1315 case glslang::EOpLessThan:
1316 case glslang::EOpGreaterThan:
1317 case glslang::EOpLessThanEqual:
1318 case glslang::EOpGreaterThanEqual:
1319 case glslang::EOpVectorEqual:
1320 case glslang::EOpVectorNotEqual:
1321 {
1322 // Map the operation to a binary
1323 binOp = node->getOp();
1324 reduceComparison = false;
1325 switch (node->getOp()) {
1326 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1327 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1328 default: binOp = node->getOp(); break;
1329 }
1330
1331 break;
1332 }
1333 case glslang::EOpMul:
1334 // compontent-wise matrix multiply
1335 binOp = glslang::EOpMul;
1336 break;
1337 case glslang::EOpOuterProduct:
1338 // two vectors multiplied to make a matrix
1339 binOp = glslang::EOpOuterProduct;
1340 break;
1341 case glslang::EOpDot:
1342 {
1343 // for scalar dot product, use multiply
1344 glslang::TIntermSequence& glslangOperands = node->getSequence();
1345 if (! glslangOperands[0]->getAsTyped()->isVector())
1346 binOp = glslang::EOpMul;
1347 break;
1348 }
1349 case glslang::EOpMod:
1350 // when an aggregate, this is the floating-point mod built-in function,
1351 // which can be emitted by the one in createBinaryOperation()
1352 binOp = glslang::EOpMod;
1353 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001354 case glslang::EOpEmitVertex:
1355 case glslang::EOpEndPrimitive:
1356 case glslang::EOpBarrier:
1357 case glslang::EOpMemoryBarrier:
1358 case glslang::EOpMemoryBarrierAtomicCounter:
1359 case glslang::EOpMemoryBarrierBuffer:
1360 case glslang::EOpMemoryBarrierImage:
1361 case glslang::EOpMemoryBarrierShared:
1362 case glslang::EOpGroupMemoryBarrier:
1363 noReturnValue = true;
1364 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1365 break;
1366
John Kessenich426394d2015-07-23 10:22:48 -06001367 case glslang::EOpAtomicAdd:
1368 case glslang::EOpAtomicMin:
1369 case glslang::EOpAtomicMax:
1370 case glslang::EOpAtomicAnd:
1371 case glslang::EOpAtomicOr:
1372 case glslang::EOpAtomicXor:
1373 case glslang::EOpAtomicExchange:
1374 case glslang::EOpAtomicCompSwap:
1375 atomic = true;
1376 break;
1377
John Kessenich140f3df2015-06-26 16:58:36 -06001378 default:
1379 break;
1380 }
1381
1382 //
1383 // See if it maps to a regular operation.
1384 //
John Kessenich140f3df2015-06-26 16:58:36 -06001385 if (binOp != glslang::EOpNull) {
1386 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1387 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1388 assert(left && right);
1389
1390 builder.clearAccessChain();
1391 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001392 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001393
1394 builder.clearAccessChain();
1395 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001396 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001397
1398 result = createBinaryOperation(binOp, precision,
1399 convertGlslangToSpvType(node->getType()), leftId, rightId,
1400 left->getType().getBasicType(), reduceComparison);
1401
1402 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001403 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001404 builder.clearAccessChain();
1405 builder.setAccessChainRValue(result);
1406
1407 return false;
1408 }
1409
John Kessenich426394d2015-07-23 10:22:48 -06001410 //
1411 // Create the list of operands.
1412 //
John Kessenich140f3df2015-06-26 16:58:36 -06001413 glslang::TIntermSequence& glslangOperands = node->getSequence();
1414 std::vector<spv::Id> operands;
1415 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1416 builder.clearAccessChain();
1417 glslangOperands[arg]->traverse(this);
1418
1419 // special case l-value operands; there are just a few
1420 bool lvalue = false;
1421 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001422 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001423 case glslang::EOpModf:
1424 if (arg == 1)
1425 lvalue = true;
1426 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001427 case glslang::EOpInterpolateAtSample:
1428 case glslang::EOpInterpolateAtOffset:
1429 if (arg == 0)
1430 lvalue = true;
1431 break;
Rex Xud4782c12015-09-06 16:30:11 +08001432 case glslang::EOpAtomicAdd:
1433 case glslang::EOpAtomicMin:
1434 case glslang::EOpAtomicMax:
1435 case glslang::EOpAtomicAnd:
1436 case glslang::EOpAtomicOr:
1437 case glslang::EOpAtomicXor:
1438 case glslang::EOpAtomicExchange:
1439 case glslang::EOpAtomicCompSwap:
1440 if (arg == 0)
1441 lvalue = true;
1442 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001443 case glslang::EOpAddCarry:
1444 case glslang::EOpSubBorrow:
1445 if (arg == 2)
1446 lvalue = true;
1447 break;
1448 case glslang::EOpUMulExtended:
1449 case glslang::EOpIMulExtended:
1450 if (arg >= 2)
1451 lvalue = true;
1452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001453 default:
1454 break;
1455 }
1456 if (lvalue)
1457 operands.push_back(builder.accessChainGetLValue());
1458 else
John Kessenich32cfd492016-02-02 12:37:46 -07001459 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001460 }
John Kessenich426394d2015-07-23 10:22:48 -06001461
1462 if (atomic) {
1463 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001464 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001465 } else {
1466 // Pass through to generic operations.
1467 switch (glslangOperands.size()) {
1468 case 0:
1469 result = createNoArgOperation(node->getOp());
1470 break;
1471 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001472 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001473 break;
1474 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001475 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001476 break;
1477 }
John Kessenich140f3df2015-06-26 16:58:36 -06001478 }
1479
1480 if (noReturnValue)
1481 return false;
1482
1483 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001484 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001485 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001486 } else {
1487 builder.clearAccessChain();
1488 builder.setAccessChainRValue(result);
1489 return false;
1490 }
1491}
1492
1493bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1494{
1495 // This path handles both if-then-else and ?:
1496 // The if-then-else has a node type of void, while
1497 // ?: has a non-void node type
1498 spv::Id result = 0;
1499 if (node->getBasicType() != glslang::EbtVoid) {
1500 // don't handle this as just on-the-fly temporaries, because there will be two names
1501 // and better to leave SSA to later passes
1502 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1503 }
1504
1505 // emit the condition before doing anything with selection
1506 node->getCondition()->traverse(this);
1507
1508 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001509 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001510
1511 if (node->getTrueBlock()) {
1512 // emit the "then" statement
1513 node->getTrueBlock()->traverse(this);
1514 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001515 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001516 }
1517
1518 if (node->getFalseBlock()) {
1519 ifBuilder.makeBeginElse();
1520 // emit the "else" statement
1521 node->getFalseBlock()->traverse(this);
1522 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001523 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001524 }
1525
1526 ifBuilder.makeEndIf();
1527
1528 if (result) {
1529 // GLSL only has r-values as the result of a :?, but
1530 // if we have an l-value, that can be more efficient if it will
1531 // become the base of a complex r-value expression, because the
1532 // next layer copies r-values into memory to use the access-chain mechanism
1533 builder.clearAccessChain();
1534 builder.setAccessChainLValue(result);
1535 }
1536
1537 return false;
1538}
1539
1540bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1541{
1542 // emit and get the condition before doing anything with switch
1543 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001544 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001545
1546 // browse the children to sort out code segments
1547 int defaultSegment = -1;
1548 std::vector<TIntermNode*> codeSegments;
1549 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1550 std::vector<int> caseValues;
1551 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1552 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1553 TIntermNode* child = *c;
1554 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001555 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001556 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001557 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001558 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1559 } else
1560 codeSegments.push_back(child);
1561 }
1562
1563 // handle the case where the last code segment is missing, due to no code
1564 // statements between the last case and the end of the switch statement
1565 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1566 (int)codeSegments.size() == defaultSegment)
1567 codeSegments.push_back(nullptr);
1568
1569 // make the switch statement
1570 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001571 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001572
1573 // emit all the code in the segments
1574 breakForLoop.push(false);
1575 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1576 builder.nextSwitchSegment(segmentBlocks, s);
1577 if (codeSegments[s])
1578 codeSegments[s]->traverse(this);
1579 else
1580 builder.addSwitchBreak();
1581 }
1582 breakForLoop.pop();
1583
1584 builder.endSwitch(segmentBlocks);
1585
1586 return false;
1587}
1588
1589void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1590{
1591 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001592 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001593
1594 builder.clearAccessChain();
1595 builder.setAccessChainRValue(constant);
1596}
1597
1598bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1599{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001600 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001601 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001602 // Spec requires back edges to target header blocks, and every header block
1603 // must dominate its merge block. Make a header block first to ensure these
1604 // conditions are met. By definition, it will contain OpLoopMerge, followed
1605 // by a block-ending branch. But we don't want to put any other body/test
1606 // instructions in it, since the body/test may have arbitrary instructions,
1607 // including merges of its own.
1608 builder.setBuildPoint(&blocks.head);
1609 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001610 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001611 spv::Block& test = builder.makeNewBlock();
1612 builder.createBranch(&test);
1613
1614 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001615 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001616 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001617 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001618 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1619
1620 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001621 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001622 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001623 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001624 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001625 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001626
1627 builder.setBuildPoint(&blocks.continue_target);
1628 if (node->getTerminal())
1629 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001630 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001631 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001632 builder.createBranch(&blocks.body);
1633
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001634 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001635 builder.setBuildPoint(&blocks.body);
1636 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001637 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001638 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001639 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001640
1641 builder.setBuildPoint(&blocks.continue_target);
1642 if (node->getTerminal())
1643 node->getTerminal()->traverse(this);
1644 if (node->getTest()) {
1645 node->getTest()->traverse(this);
1646 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001647 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001648 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001649 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001650 // TODO: unless there was a break/return/discard instruction
1651 // somewhere in the body, this is an infinite loop, so we should
1652 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001653 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654 }
John Kessenich140f3df2015-06-26 16:58:36 -06001655 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001656 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001657 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001658 return false;
1659}
1660
1661bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1662{
1663 if (node->getExpression())
1664 node->getExpression()->traverse(this);
1665
1666 switch (node->getFlowOp()) {
1667 case glslang::EOpKill:
1668 builder.makeDiscard();
1669 break;
1670 case glslang::EOpBreak:
1671 if (breakForLoop.top())
1672 builder.createLoopExit();
1673 else
1674 builder.addSwitchBreak();
1675 break;
1676 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001677 builder.createLoopContinue();
1678 break;
1679 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001680 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001681 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001682 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001683 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 builder.clearAccessChain();
1686 break;
1687
1688 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001689 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001690 break;
1691 }
1692
1693 return false;
1694}
1695
1696spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1697{
1698 // First, steer off constants, which are not SPIR-V variables, but
1699 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001700 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001701 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001702 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001703 }
1704
1705 // Now, handle actual variables
1706 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1707 spv::Id spvType = convertGlslangToSpvType(node->getType());
1708
1709 const char* name = node->getName().c_str();
1710 if (glslang::IsAnonymous(name))
1711 name = "";
1712
1713 return builder.createVariable(storageClass, spvType, name);
1714}
1715
1716// Return type Id of the sampled type.
1717spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1718{
1719 switch (sampler.type) {
1720 case glslang::EbtFloat: return builder.makeFloatType(32);
1721 case glslang::EbtInt: return builder.makeIntType(32);
1722 case glslang::EbtUint: return builder.makeUintType(32);
1723 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001724 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001725 return builder.makeFloatType(32);
1726 }
1727}
1728
John Kessenich3ac051e2015-12-20 11:29:16 -07001729// Convert from a glslang type to an SPV type, by calling into a
1730// recursive version of this function. This establishes the inherited
1731// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001732spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1733{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001734 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001735}
1736
1737// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001738// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001739spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001740{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001741 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001742
1743 switch (type.getBasicType()) {
1744 case glslang::EbtVoid:
1745 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001746 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001747 break;
1748 case glslang::EbtFloat:
1749 spvType = builder.makeFloatType(32);
1750 break;
1751 case glslang::EbtDouble:
1752 spvType = builder.makeFloatType(64);
1753 break;
1754 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001755 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1756 // a 32-bit int where non-0 means true.
1757 if (explicitLayout != glslang::ElpNone)
1758 spvType = builder.makeUintType(32);
1759 else
1760 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001761 break;
1762 case glslang::EbtInt:
1763 spvType = builder.makeIntType(32);
1764 break;
1765 case glslang::EbtUint:
1766 spvType = builder.makeUintType(32);
1767 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001768 case glslang::EbtInt64:
1769 builder.addCapability(spv::CapabilityInt64);
1770 spvType = builder.makeIntType(64);
1771 break;
1772 case glslang::EbtUint64:
1773 builder.addCapability(spv::CapabilityInt64);
1774 spvType = builder.makeUintType(64);
1775 break;
John Kessenich426394d2015-07-23 10:22:48 -06001776 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001777 logger->tbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
John Kessenich426394d2015-07-23 10:22:48 -06001778 spvType = builder.makeUintType(32);
1779 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001780 case glslang::EbtSampler:
1781 {
1782 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001783 if (sampler.sampler) {
1784 // pure sampler
1785 spvType = builder.makeSamplerType();
1786 } else {
1787 // an image is present, make its type
1788 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1789 sampler.image ? 2 : 1, TranslateImageFormat(type));
1790 if (sampler.combined) {
1791 // already has both image and sampler, make the combined type
1792 spvType = builder.makeSampledImageType(spvType);
1793 }
John Kessenich55e7d112015-11-15 21:33:39 -07001794 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001795 }
John Kessenich140f3df2015-06-26 16:58:36 -06001796 break;
1797 case glslang::EbtStruct:
1798 case glslang::EbtBlock:
1799 {
1800 // If we've seen this struct type, return it
1801 const glslang::TTypeList* glslangStruct = type.getStruct();
1802 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001803
1804 // Try to share structs for different layouts, but not yet for other
1805 // kinds of qualification (primarily not yet including interpolant qualification).
1806 if (! HasNonLayoutQualifiers(qualifier))
1807 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1808 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001809 break;
1810
1811 // else, we haven't seen it...
1812
1813 // Create a vector of struct types for SPIR-V to consume
1814 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1815 if (type.getBasicType() == glslang::EbtBlock)
1816 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001817 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001818 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1819 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1820 if (glslangType.hiddenMember()) {
1821 ++memberDelta;
1822 if (type.getBasicType() == glslang::EbtBlock)
1823 memberRemapper[glslangStruct][i] = -1;
1824 } else {
1825 if (type.getBasicType() == glslang::EbtBlock)
1826 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827 // modify just this child's view of the qualifier
1828 glslang::TQualifier subQualifier = glslangType.getQualifier();
1829 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001830
1831 // manually inherit location; it's more complex
1832 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1833 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1834 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001835 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001836
1837 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001838 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001839 }
1840 }
1841
1842 // Make the SPIR-V type
1843 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001844 if (! HasNonLayoutQualifiers(qualifier))
1845 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001846
1847 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001848 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001849 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001850 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1851 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1852 int member = i;
1853 if (type.getBasicType() == glslang::EbtBlock)
1854 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001855
John Kesseniche0b6cad2015-12-24 10:30:13 -07001856 // modify just this child's view of the qualifier
1857 glslang::TQualifier subQualifier = glslangType.getQualifier();
1858 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001859
John Kessenich140f3df2015-06-26 16:58:36 -06001860 // using -1 above to indicate a hidden member
1861 if (member >= 0) {
1862 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001863 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001864 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001865 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1866 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001867
Rex Xu1da878f2016-02-21 20:59:01 +08001868 if (qualifier.storage == glslang::EvqBuffer) {
1869 std::vector<spv::Decoration> memory;
1870 TranslateMemoryDecoration(subQualifier, memory);
1871 for (unsigned int i = 0; i < memory.size(); ++i)
1872 addMemberDecoration(spvType, member, memory[i]);
1873 }
1874
John Kessenich09677482016-02-19 12:21:50 -07001875 // compute location decoration; tricky based on whether inheritance is at play
1876 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1877 // probably move to the linker stage of the front end proper, and just have the
1878 // answer sitting already distributed throughout the individual member locations.
1879 int location = -1; // will only decorate if present or inherited
1880 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1881 location = subQualifier.layoutLocation;
1882 else if (qualifier.hasLocation()) // inheritance
1883 location = qualifier.layoutLocation + locationOffset;
1884 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001885 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001886 if (location >= 0)
1887 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1888
1889 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001890 if (glslangType.getQualifier().hasComponent())
1891 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1892 if (glslangType.getQualifier().hasXfbOffset())
1893 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001894 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001895 // figure out what to do with offset, which is accumulating
1896 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001897 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001898 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001899 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001900 offset = nextOffset;
1901 }
John Kessenich140f3df2015-06-26 16:58:36 -06001902
John Kessenichf85e8062015-12-19 13:57:10 -07001903 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001904 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001905
John Kessenich140f3df2015-06-26 16:58:36 -06001906 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001907 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1908 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001909 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001910 }
1911 }
1912
1913 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001914 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001915 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001916 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001917 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001918 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001919 }
John Kessenich140f3df2015-06-26 16:58:36 -06001920 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001921 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001922 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001923 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001924 if (type.getQualifier().hasXfbBuffer())
1925 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1926 }
1927 }
1928 break;
1929 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001930 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001931 break;
1932 }
1933
1934 if (type.isMatrix())
1935 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1936 else {
1937 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1938 if (type.getVectorSize() > 1)
1939 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1940 }
1941
1942 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001943 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1944
John Kessenichc9a80832015-09-12 12:17:44 -06001945 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001946 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001947 // We need to decorate array strides for types needing explicit layout, except blocks.
1948 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001949 // Use a dummy glslang type for querying internal strides of
1950 // arrays of arrays, but using just a one-dimensional array.
1951 glslang::TType simpleArrayType(type, 0); // deference type of the array
1952 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1953 simpleArrayType.getArraySizes().dereference();
1954
1955 // Will compute the higher-order strides here, rather than making a whole
1956 // pile of types and doing repetitive recursion on their contents.
1957 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1958 }
John Kessenichf8842e52016-01-04 19:22:56 -07001959
1960 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001961 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001962 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001963 if (stride > 0)
1964 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001965 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001966 }
1967 } else {
1968 // single-dimensional array, and don't yet have stride
1969
John Kessenichf8842e52016-01-04 19:22:56 -07001970 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001971 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1972 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001973 }
John Kessenich31ed4832015-09-09 17:51:38 -06001974
John Kessenichc9a80832015-09-12 12:17:44 -06001975 // Do the outer dimension, which might not be known for a runtime-sized array
1976 if (type.isRuntimeSizedArray()) {
1977 spvType = builder.makeRuntimeArray(spvType);
1978 } else {
1979 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001980 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001981 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001982 if (stride > 0)
1983 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001984 }
1985
1986 return spvType;
1987}
1988
John Kessenich6c292d32016-02-15 20:58:50 -07001989// Turn the expression forming the array size into an id.
1990// This is not quite trivial, because of specialization constants.
1991// Sometimes, a raw constant is turned into an Id, and sometimes
1992// a specialization constant expression is.
1993spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1994{
1995 // First, see if this is sized with a node, meaning a specialization constant:
1996 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1997 if (specNode != nullptr) {
1998 builder.clearAccessChain();
1999 specNode->traverse(this);
2000 return accessChainLoad(specNode->getAsTyped()->getType());
2001 }
2002
2003 // Otherwise, need a compile-time (front end) size, get it:
2004 int size = arraySizes.getDimSize(dim);
2005 assert(size > 0);
2006 return builder.makeUintConstant(size);
2007}
2008
John Kessenich103bef92016-02-08 21:38:15 -07002009// Wrap the builder's accessChainLoad to:
2010// - localize handling of RelaxedPrecision
2011// - use the SPIR-V inferred type instead of another conversion of the glslang type
2012// (avoids unnecessary work and possible type punning for structures)
2013// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002014spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2015{
John Kessenich103bef92016-02-08 21:38:15 -07002016 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2017 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2018
2019 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002020 if (type.getBasicType() == glslang::EbtBool) {
2021 if (builder.isScalarType(nominalTypeId)) {
2022 // Conversion for bool
2023 spv::Id boolType = builder.makeBoolType();
2024 if (nominalTypeId != boolType)
2025 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2026 } else if (builder.isVectorType(nominalTypeId)) {
2027 // Conversion for bvec
2028 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2029 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2030 if (nominalTypeId != bvecType)
2031 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2032 }
2033 }
John Kessenich103bef92016-02-08 21:38:15 -07002034
2035 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002036}
2037
Rex Xu27253232016-02-23 17:51:09 +08002038// Wrap the builder's accessChainStore to:
2039// - do conversion of concrete to abstract type
2040void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2041{
2042 // Need to convert to abstract types when necessary
2043 if (type.getBasicType() == glslang::EbtBool) {
2044 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2045
2046 if (builder.isScalarType(nominalTypeId)) {
2047 // Conversion for bool
2048 spv::Id boolType = builder.makeBoolType();
2049 if (nominalTypeId != boolType) {
2050 spv::Id zero = builder.makeUintConstant(0);
2051 spv::Id one = builder.makeUintConstant(1);
2052 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2053 }
2054 } else if (builder.isVectorType(nominalTypeId)) {
2055 // Conversion for bvec
2056 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2057 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2058 if (nominalTypeId != bvecType) {
2059 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2060 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2061 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2062 }
2063 }
2064 }
2065
2066 builder.accessChainStore(rvalue);
2067}
2068
John Kessenichf85e8062015-12-19 13:57:10 -07002069// Decide whether or not this type should be
2070// decorated with offsets and strides, and if so
2071// whether std140 or std430 rules should be applied.
2072glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002073{
John Kessenichf85e8062015-12-19 13:57:10 -07002074 // has to be a block
2075 if (type.getBasicType() != glslang::EbtBlock)
2076 return glslang::ElpNone;
2077
2078 // has to be a uniform or buffer block
2079 if (type.getQualifier().storage != glslang::EvqUniform &&
2080 type.getQualifier().storage != glslang::EvqBuffer)
2081 return glslang::ElpNone;
2082
2083 // return the layout to use
2084 switch (type.getQualifier().layoutPacking) {
2085 case glslang::ElpStd140:
2086 case glslang::ElpStd430:
2087 return type.getQualifier().layoutPacking;
2088 default:
2089 return glslang::ElpNone;
2090 }
John Kessenich31ed4832015-09-09 17:51:38 -06002091}
2092
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002093// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002094int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002095{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002096 int size;
John Kessenich49987892015-12-29 17:11:44 -07002097 int stride;
2098 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002099
2100 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002101}
2102
John Kessenich49987892015-12-29 17:11:44 -07002103// 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 -07002104// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002105int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002106{
John Kessenich49987892015-12-29 17:11:44 -07002107 glslang::TType elementType;
2108 elementType.shallowCopy(matrixType);
2109 elementType.clearArraySizes();
2110
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002111 int size;
John Kessenich49987892015-12-29 17:11:44 -07002112 int stride;
2113 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2114
2115 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002116}
2117
John Kessenich5e4b1242015-08-06 22:53:06 -06002118// Given a member type of a struct, realign the current offset for it, and compute
2119// the next (not yet aligned) offset for the next member, which will get aligned
2120// on the next call.
2121// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2122// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2123// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002124void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002125 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002126{
2127 // this will get a positive value when deemed necessary
2128 nextOffset = -1;
2129
John Kessenich5e4b1242015-08-06 22:53:06 -06002130 // override anything in currentOffset with user-set offset
2131 if (memberType.getQualifier().hasOffset())
2132 currentOffset = memberType.getQualifier().layoutOffset;
2133
2134 // It could be that current linker usage in glslang updated all the layoutOffset,
2135 // in which case the following code does not matter. But, that's not quite right
2136 // once cross-compilation unit GLSL validation is done, as the original user
2137 // settings are needed in layoutOffset, and then the following will come into play.
2138
John Kessenichf85e8062015-12-19 13:57:10 -07002139 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002140 if (! memberType.getQualifier().hasOffset())
2141 currentOffset = -1;
2142
2143 return;
2144 }
2145
John Kessenichf85e8062015-12-19 13:57:10 -07002146 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002147 if (currentOffset < 0)
2148 currentOffset = 0;
2149
2150 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2151 // but possibly not yet correctly aligned.
2152
2153 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002154 int dummyStride;
2155 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002156 glslang::RoundToPow2(currentOffset, memberAlignment);
2157 nextOffset = currentOffset + memberSize;
2158}
2159
John Kessenich140f3df2015-06-26 16:58:36 -06002160bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2161{
John Kessenich4d65ee32016-03-12 18:17:47 -07002162 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002163 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002164 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002165}
2166
2167// Make all the functions, skeletally, without actually visiting their bodies.
2168void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2169{
2170 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2171 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2172 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2173 continue;
2174
2175 // We're on a user function. Set up the basic interface for the function now,
2176 // so that it's available to call.
2177 // Translating the body will happen later.
2178 //
2179 // Typically (except for a "const in" parameter), an address will be passed to the
2180 // function. What it is an address of varies:
2181 //
2182 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2183 // so that write needs to be to a copy, hence the address of a copy works.
2184 //
2185 // - "const in" parameters can just be the r-value, as no writes need occur.
2186 //
2187 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2188 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2189
2190 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002191 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002192 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2193
2194 for (int p = 0; p < (int)parameters.size(); ++p) {
2195 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2196 spv::Id typeId = convertGlslangToSpvType(paramType);
2197 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2198 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2199 else
2200 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002201 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002202 paramTypes.push_back(typeId);
2203 }
2204
2205 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002206 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2207 convertGlslangToSpvType(glslFunction->getType()),
2208 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002209
2210 // Track function to emit/call later
2211 functionMap[glslFunction->getName().c_str()] = function;
2212
2213 // Set the parameter id's
2214 for (int p = 0; p < (int)parameters.size(); ++p) {
2215 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2216 // give a name too
2217 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2218 }
2219 }
2220}
2221
2222// Process all the initializers, while skipping the functions and link objects
2223void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2224{
2225 builder.setBuildPoint(shaderEntry->getLastBlock());
2226 for (int i = 0; i < (int)initializers.size(); ++i) {
2227 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2228 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2229
2230 // We're on a top-level node that's not a function. Treat as an initializer, whose
2231 // code goes into the beginning of main.
2232 initializer->traverse(this);
2233 }
2234 }
2235}
2236
2237// Process all the functions, while skipping initializers.
2238void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2239{
2240 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2241 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2242 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2243 node->traverse(this);
2244 }
2245}
2246
2247void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2248{
2249 // SPIR-V functions should already be in the functionMap from the prepass
2250 // that called makeFunctions().
2251 spv::Function* function = functionMap[node->getName().c_str()];
2252 spv::Block* functionBlock = function->getEntryBlock();
2253 builder.setBuildPoint(functionBlock);
2254}
2255
Rex Xu04db3f52015-09-16 11:44:02 +08002256void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002257{
Rex Xufc618912015-09-09 16:42:49 +08002258 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002259
2260 glslang::TSampler sampler = {};
2261 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002262 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002263 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2264 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2265 }
2266
John Kessenich140f3df2015-06-26 16:58:36 -06002267 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2268 builder.clearAccessChain();
2269 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002270
2271 // Special case l-value operands
2272 bool lvalue = false;
2273 switch (node.getOp()) {
2274 case glslang::EOpImageAtomicAdd:
2275 case glslang::EOpImageAtomicMin:
2276 case glslang::EOpImageAtomicMax:
2277 case glslang::EOpImageAtomicAnd:
2278 case glslang::EOpImageAtomicOr:
2279 case glslang::EOpImageAtomicXor:
2280 case glslang::EOpImageAtomicExchange:
2281 case glslang::EOpImageAtomicCompSwap:
2282 if (i == 0)
2283 lvalue = true;
2284 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002285 case glslang::EOpSparseImageLoad:
2286 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2287 lvalue = true;
2288 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002289 case glslang::EOpSparseTexture:
2290 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2291 lvalue = true;
2292 break;
2293 case glslang::EOpSparseTextureClamp:
2294 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2295 lvalue = true;
2296 break;
2297 case glslang::EOpSparseTextureLod:
2298 case glslang::EOpSparseTextureOffset:
2299 if (i == 3)
2300 lvalue = true;
2301 break;
2302 case glslang::EOpSparseTextureFetch:
2303 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2304 lvalue = true;
2305 break;
2306 case glslang::EOpSparseTextureFetchOffset:
2307 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2308 lvalue = true;
2309 break;
2310 case glslang::EOpSparseTextureLodOffset:
2311 case glslang::EOpSparseTextureGrad:
2312 case glslang::EOpSparseTextureOffsetClamp:
2313 if (i == 4)
2314 lvalue = true;
2315 break;
2316 case glslang::EOpSparseTextureGradOffset:
2317 case glslang::EOpSparseTextureGradClamp:
2318 if (i == 5)
2319 lvalue = true;
2320 break;
2321 case glslang::EOpSparseTextureGradOffsetClamp:
2322 if (i == 6)
2323 lvalue = true;
2324 break;
2325 case glslang::EOpSparseTextureGather:
2326 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2327 lvalue = true;
2328 break;
2329 case glslang::EOpSparseTextureGatherOffset:
2330 case glslang::EOpSparseTextureGatherOffsets:
2331 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2332 lvalue = true;
2333 break;
Rex Xufc618912015-09-09 16:42:49 +08002334 default:
2335 break;
2336 }
2337
Rex Xu6b86d492015-09-16 17:48:22 +08002338 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002339 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002340 else
John Kessenich32cfd492016-02-02 12:37:46 -07002341 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002342 }
2343}
2344
John Kessenichfc51d282015-08-19 13:34:18 -06002345void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002346{
John Kessenichfc51d282015-08-19 13:34:18 -06002347 builder.clearAccessChain();
2348 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002349 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002350}
John Kessenich140f3df2015-06-26 16:58:36 -06002351
John Kessenichfc51d282015-08-19 13:34:18 -06002352spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2353{
Rex Xufc618912015-09-09 16:42:49 +08002354 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002355 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002356 }
2357
John Kessenichfc51d282015-08-19 13:34:18 -06002358 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002359 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2360 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2361 std::vector<spv::Id> arguments;
2362 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002363 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002364 else
2365 translateArguments(*node->getAsUnaryNode(), arguments);
2366 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2367
2368 spv::Builder::TextureParameters params = { };
2369 params.sampler = arguments[0];
2370
Rex Xu04db3f52015-09-16 11:44:02 +08002371 glslang::TCrackedTextureOp cracked;
2372 node->crackTexture(sampler, cracked);
2373
John Kessenichfc51d282015-08-19 13:34:18 -06002374 // Check for queries
2375 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002376 // a sampled image needs to have the image extracted first
2377 if (builder.isSampledImage(params.sampler))
2378 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002379 switch (node->getOp()) {
2380 case glslang::EOpImageQuerySize:
2381 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002382 if (arguments.size() > 1) {
2383 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002384 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002385 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002387 case glslang::EOpImageQuerySamples:
2388 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002389 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002390 case glslang::EOpTextureQueryLod:
2391 params.coords = arguments[1];
2392 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2393 case glslang::EOpTextureQueryLevels:
2394 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002395 case glslang::EOpSparseTexelsResident:
2396 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002397 default:
2398 assert(0);
2399 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002400 }
John Kessenich140f3df2015-06-26 16:58:36 -06002401 }
2402
Rex Xufc618912015-09-09 16:42:49 +08002403 // Check for image functions other than queries
2404 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002405 std::vector<spv::Id> operands;
2406 auto opIt = arguments.begin();
2407 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002408
2409 // Handle subpass operations
2410 // TODO: GLSL should change to have the "MS" only on the type rather than the
2411 // built-in function.
2412 if (cracked.subpass) {
2413 // add on the (0,0) coordinate
2414 spv::Id zero = builder.makeIntConstant(0);
2415 std::vector<spv::Id> comps;
2416 comps.push_back(zero);
2417 comps.push_back(zero);
2418 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2419 if (sampler.ms) {
2420 operands.push_back(spv::ImageOperandsSampleMask);
2421 operands.push_back(*(opIt++));
2422 }
2423 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2424 }
2425
John Kessenich56bab042015-09-16 10:54:31 -06002426 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002427 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002428 if (sampler.ms) {
2429 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002430 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002431 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002432 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2433 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002434 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002435 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002436 if (sampler.ms) {
2437 operands.push_back(*(opIt + 1));
2438 operands.push_back(spv::ImageOperandsSampleMask);
2439 operands.push_back(*opIt);
2440 } else
2441 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002442 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002443 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2444 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002445 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002446 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2447 builder.addCapability(spv::CapabilitySparseResidency);
2448 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2449 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2450
2451 if (sampler.ms) {
2452 operands.push_back(spv::ImageOperandsSampleMask);
2453 operands.push_back(*opIt++);
2454 }
2455
2456 // Create the return type that was a special structure
2457 spv::Id texelOut = *opIt;
2458 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2459 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2460 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2461
2462 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2463
2464 // Decode the return type
2465 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2466 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002467 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002468 // Process image atomic operations
2469
2470 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2471 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002472 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002473
Rex Xufc618912015-09-09 16:42:49 +08002474 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002475 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002476
2477 std::vector<spv::Id> operands;
2478 operands.push_back(pointer);
2479 for (; opIt != arguments.end(); ++opIt)
2480 operands.push_back(*opIt);
2481
Rex Xu04db3f52015-09-16 11:44:02 +08002482 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002483 }
2484 }
2485
2486 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002487 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002488 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2489
John Kessenichfc51d282015-08-19 13:34:18 -06002490 // check for bias argument
2491 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002492 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002493 int nonBiasArgCount = 2;
2494 if (cracked.offset)
2495 ++nonBiasArgCount;
2496 if (cracked.grad)
2497 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002498 if (cracked.lodClamp)
2499 ++nonBiasArgCount;
2500 if (sparse)
2501 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002502
2503 if ((int)arguments.size() > nonBiasArgCount)
2504 bias = true;
2505 }
2506
John Kessenichfc51d282015-08-19 13:34:18 -06002507 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002508
John Kessenichfc51d282015-08-19 13:34:18 -06002509 params.coords = arguments[1];
2510 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002511 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002512
2513 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002514 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002515 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002516 ++extraArgs;
2517 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002518 params.Dref = arguments[2];
2519 ++extraArgs;
2520 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002521 std::vector<spv::Id> indexes;
2522 int comp;
2523 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002524 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002525 else
2526 comp = builder.getNumComponents(params.coords) - 1;
2527 indexes.push_back(comp);
2528 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2529 }
2530 if (cracked.lod) {
2531 params.lod = arguments[2];
2532 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002533 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2534 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2535 noImplicitLod = true;
2536 }
2537 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002538 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002539 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002540 }
2541 if (cracked.grad) {
2542 params.gradX = arguments[2 + extraArgs];
2543 params.gradY = arguments[3 + extraArgs];
2544 extraArgs += 2;
2545 }
John Kessenich55e7d112015-11-15 21:33:39 -07002546 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002547 params.offset = arguments[2 + extraArgs];
2548 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002549 } else if (cracked.offsets) {
2550 params.offsets = arguments[2 + extraArgs];
2551 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002552 }
Rex Xu48edadf2015-12-31 16:11:41 +08002553 if (cracked.lodClamp) {
2554 params.lodClamp = arguments[2 + extraArgs];
2555 ++extraArgs;
2556 }
2557 if (sparse) {
2558 params.texelOut = arguments[2 + extraArgs];
2559 ++extraArgs;
2560 }
John Kessenichfc51d282015-08-19 13:34:18 -06002561 if (bias) {
2562 params.bias = arguments[2 + extraArgs];
2563 ++extraArgs;
2564 }
John Kessenich55e7d112015-11-15 21:33:39 -07002565 if (cracked.gather && ! sampler.shadow) {
2566 // default component is 0, if missing, otherwise an argument
2567 if (2 + extraArgs < (int)arguments.size()) {
2568 params.comp = arguments[2 + extraArgs];
2569 ++extraArgs;
2570 } else {
2571 params.comp = builder.makeIntConstant(0);
2572 }
2573 }
John Kessenichfc51d282015-08-19 13:34:18 -06002574
John Kessenich019f08f2016-02-15 15:40:42 -07002575 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002576}
2577
2578spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2579{
2580 // Grab the function's pointer from the previously created function
2581 spv::Function* function = functionMap[node->getName().c_str()];
2582 if (! function)
2583 return 0;
2584
2585 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2586 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2587
2588 // See comments in makeFunctions() for details about the semantics for parameter passing.
2589 //
2590 // These imply we need a four step process:
2591 // 1. Evaluate the arguments
2592 // 2. Allocate and make copies of in, out, and inout arguments
2593 // 3. Make the call
2594 // 4. Copy back the results
2595
2596 // 1. Evaluate the arguments
2597 std::vector<spv::Builder::AccessChain> lValues;
2598 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002599 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002600 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2601 // build l-value
2602 builder.clearAccessChain();
2603 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002604 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002605 // keep outputs as l-values, evaluate input-only as r-values
2606 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2607 // save l-value
2608 lValues.push_back(builder.getAccessChain());
2609 } else {
2610 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002611 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002612 }
2613 }
2614
2615 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2616 // copy the original into that space.
2617 //
2618 // Also, build up the list of actual arguments to pass in for the call
2619 int lValueCount = 0;
2620 int rValueCount = 0;
2621 std::vector<spv::Id> spvArgs;
2622 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2623 spv::Id arg;
2624 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2625 // need space to hold the copy
2626 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2627 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2628 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2629 // need to copy the input into output space
2630 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002631 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002632 builder.createStore(copy, arg);
2633 }
2634 ++lValueCount;
2635 } else {
2636 arg = rValues[rValueCount];
2637 ++rValueCount;
2638 }
2639 spvArgs.push_back(arg);
2640 }
2641
2642 // 3. Make the call.
2643 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002644 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002645
2646 // 4. Copy back out an "out" arguments.
2647 lValueCount = 0;
2648 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2649 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2650 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2651 spv::Id copy = builder.createLoad(spvArgs[a]);
2652 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002653 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002654 }
2655 ++lValueCount;
2656 }
2657 }
2658
2659 return result;
2660}
2661
2662// Translate AST operation to SPV operation, already having SPV-based operands/types.
2663spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2664 spv::Id typeId, spv::Id left, spv::Id right,
2665 glslang::TBasicType typeProxy, bool reduceComparison)
2666{
Rex Xu8ff43de2016-04-22 16:51:45 +08002667 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002668 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002669 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002670
2671 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002672 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002673 bool comparison = false;
2674
2675 switch (op) {
2676 case glslang::EOpAdd:
2677 case glslang::EOpAddAssign:
2678 if (isFloat)
2679 binOp = spv::OpFAdd;
2680 else
2681 binOp = spv::OpIAdd;
2682 break;
2683 case glslang::EOpSub:
2684 case glslang::EOpSubAssign:
2685 if (isFloat)
2686 binOp = spv::OpFSub;
2687 else
2688 binOp = spv::OpISub;
2689 break;
2690 case glslang::EOpMul:
2691 case glslang::EOpMulAssign:
2692 if (isFloat)
2693 binOp = spv::OpFMul;
2694 else
2695 binOp = spv::OpIMul;
2696 break;
2697 case glslang::EOpVectorTimesScalar:
2698 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002699 if (isFloat) {
2700 if (builder.isVector(right))
2701 std::swap(left, right);
2702 assert(builder.isScalar(right));
2703 needMatchingVectors = false;
2704 binOp = spv::OpVectorTimesScalar;
2705 } else
2706 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002707 break;
2708 case glslang::EOpVectorTimesMatrix:
2709 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002710 binOp = spv::OpVectorTimesMatrix;
2711 break;
2712 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002713 binOp = spv::OpMatrixTimesVector;
2714 break;
2715 case glslang::EOpMatrixTimesScalar:
2716 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002717 binOp = spv::OpMatrixTimesScalar;
2718 break;
2719 case glslang::EOpMatrixTimesMatrix:
2720 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002721 binOp = spv::OpMatrixTimesMatrix;
2722 break;
2723 case glslang::EOpOuterProduct:
2724 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002725 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002726 break;
2727
2728 case glslang::EOpDiv:
2729 case glslang::EOpDivAssign:
2730 if (isFloat)
2731 binOp = spv::OpFDiv;
2732 else if (isUnsigned)
2733 binOp = spv::OpUDiv;
2734 else
2735 binOp = spv::OpSDiv;
2736 break;
2737 case glslang::EOpMod:
2738 case glslang::EOpModAssign:
2739 if (isFloat)
2740 binOp = spv::OpFMod;
2741 else if (isUnsigned)
2742 binOp = spv::OpUMod;
2743 else
2744 binOp = spv::OpSMod;
2745 break;
2746 case glslang::EOpRightShift:
2747 case glslang::EOpRightShiftAssign:
2748 if (isUnsigned)
2749 binOp = spv::OpShiftRightLogical;
2750 else
2751 binOp = spv::OpShiftRightArithmetic;
2752 break;
2753 case glslang::EOpLeftShift:
2754 case glslang::EOpLeftShiftAssign:
2755 binOp = spv::OpShiftLeftLogical;
2756 break;
2757 case glslang::EOpAnd:
2758 case glslang::EOpAndAssign:
2759 binOp = spv::OpBitwiseAnd;
2760 break;
2761 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002762 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002763 binOp = spv::OpLogicalAnd;
2764 break;
2765 case glslang::EOpInclusiveOr:
2766 case glslang::EOpInclusiveOrAssign:
2767 binOp = spv::OpBitwiseOr;
2768 break;
2769 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002770 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002771 binOp = spv::OpLogicalOr;
2772 break;
2773 case glslang::EOpExclusiveOr:
2774 case glslang::EOpExclusiveOrAssign:
2775 binOp = spv::OpBitwiseXor;
2776 break;
2777 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002778 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002779 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002780 break;
2781
2782 case glslang::EOpLessThan:
2783 case glslang::EOpGreaterThan:
2784 case glslang::EOpLessThanEqual:
2785 case glslang::EOpGreaterThanEqual:
2786 case glslang::EOpEqual:
2787 case glslang::EOpNotEqual:
2788 case glslang::EOpVectorEqual:
2789 case glslang::EOpVectorNotEqual:
2790 comparison = true;
2791 break;
2792 default:
2793 break;
2794 }
2795
John Kessenich7c1aa102015-10-15 13:29:11 -06002796 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002797 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002798 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002799 if (builder.isMatrix(left) || builder.isMatrix(right))
2800 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002801
2802 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002803 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002804 builder.promoteScalar(precision, left, right);
2805
John Kessenich32cfd492016-02-02 12:37:46 -07002806 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002807 }
2808
2809 if (! comparison)
2810 return 0;
2811
John Kessenich7c1aa102015-10-15 13:29:11 -06002812 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002813
2814 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2815 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2816
John Kessenich22118352015-12-21 20:54:09 -07002817 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002818 }
2819
2820 switch (op) {
2821 case glslang::EOpLessThan:
2822 if (isFloat)
2823 binOp = spv::OpFOrdLessThan;
2824 else if (isUnsigned)
2825 binOp = spv::OpULessThan;
2826 else
2827 binOp = spv::OpSLessThan;
2828 break;
2829 case glslang::EOpGreaterThan:
2830 if (isFloat)
2831 binOp = spv::OpFOrdGreaterThan;
2832 else if (isUnsigned)
2833 binOp = spv::OpUGreaterThan;
2834 else
2835 binOp = spv::OpSGreaterThan;
2836 break;
2837 case glslang::EOpLessThanEqual:
2838 if (isFloat)
2839 binOp = spv::OpFOrdLessThanEqual;
2840 else if (isUnsigned)
2841 binOp = spv::OpULessThanEqual;
2842 else
2843 binOp = spv::OpSLessThanEqual;
2844 break;
2845 case glslang::EOpGreaterThanEqual:
2846 if (isFloat)
2847 binOp = spv::OpFOrdGreaterThanEqual;
2848 else if (isUnsigned)
2849 binOp = spv::OpUGreaterThanEqual;
2850 else
2851 binOp = spv::OpSGreaterThanEqual;
2852 break;
2853 case glslang::EOpEqual:
2854 case glslang::EOpVectorEqual:
2855 if (isFloat)
2856 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002857 else if (isBool)
2858 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002859 else
2860 binOp = spv::OpIEqual;
2861 break;
2862 case glslang::EOpNotEqual:
2863 case glslang::EOpVectorNotEqual:
2864 if (isFloat)
2865 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002866 else if (isBool)
2867 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002868 else
2869 binOp = spv::OpINotEqual;
2870 break;
2871 default:
2872 break;
2873 }
2874
John Kessenich32cfd492016-02-02 12:37:46 -07002875 if (binOp != spv::OpNop)
2876 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002877
2878 return 0;
2879}
2880
John Kessenich04bb8a02015-12-12 12:28:14 -07002881//
2882// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2883// These can be any of:
2884//
2885// matrix * scalar
2886// scalar * matrix
2887// matrix * matrix linear algebraic
2888// matrix * vector
2889// vector * matrix
2890// matrix * matrix componentwise
2891// matrix op matrix op in {+, -, /}
2892// matrix op scalar op in {+, -, /}
2893// scalar op matrix op in {+, -, /}
2894//
2895spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2896{
2897 bool firstClass = true;
2898
2899 // First, handle first-class matrix operations (* and matrix/scalar)
2900 switch (op) {
2901 case spv::OpFDiv:
2902 if (builder.isMatrix(left) && builder.isScalar(right)) {
2903 // turn matrix / scalar into a multiply...
2904 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2905 op = spv::OpMatrixTimesScalar;
2906 } else
2907 firstClass = false;
2908 break;
2909 case spv::OpMatrixTimesScalar:
2910 if (builder.isMatrix(right))
2911 std::swap(left, right);
2912 assert(builder.isScalar(right));
2913 break;
2914 case spv::OpVectorTimesMatrix:
2915 assert(builder.isVector(left));
2916 assert(builder.isMatrix(right));
2917 break;
2918 case spv::OpMatrixTimesVector:
2919 assert(builder.isMatrix(left));
2920 assert(builder.isVector(right));
2921 break;
2922 case spv::OpMatrixTimesMatrix:
2923 assert(builder.isMatrix(left));
2924 assert(builder.isMatrix(right));
2925 break;
2926 default:
2927 firstClass = false;
2928 break;
2929 }
2930
John Kessenich32cfd492016-02-02 12:37:46 -07002931 if (firstClass)
2932 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002933
2934 // Handle component-wise +, -, *, and / for all combinations of type.
2935 // The result type of all of them is the same type as the (a) matrix operand.
2936 // The algorithm is to:
2937 // - break the matrix(es) into vectors
2938 // - smear any scalar to a vector
2939 // - do vector operations
2940 // - make a matrix out the vector results
2941 switch (op) {
2942 case spv::OpFAdd:
2943 case spv::OpFSub:
2944 case spv::OpFDiv:
2945 case spv::OpFMul:
2946 {
2947 // one time set up...
2948 bool leftMat = builder.isMatrix(left);
2949 bool rightMat = builder.isMatrix(right);
2950 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2951 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2952 spv::Id scalarType = builder.getScalarTypeId(typeId);
2953 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2954 std::vector<spv::Id> results;
2955 spv::Id smearVec = spv::NoResult;
2956 if (builder.isScalar(left))
2957 smearVec = builder.smearScalar(precision, left, vecType);
2958 else if (builder.isScalar(right))
2959 smearVec = builder.smearScalar(precision, right, vecType);
2960
2961 // do each vector op
2962 for (unsigned int c = 0; c < numCols; ++c) {
2963 std::vector<unsigned int> indexes;
2964 indexes.push_back(c);
2965 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2966 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2967 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2968 builder.setPrecision(results.back(), precision);
2969 }
2970
2971 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002972 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002973 }
2974 default:
2975 assert(0);
2976 return spv::NoResult;
2977 }
2978}
2979
Rex Xu04db3f52015-09-16 11:44:02 +08002980spv::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 -06002981{
2982 spv::Op unaryOp = spv::OpNop;
2983 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08002984 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08002985 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002986
2987 switch (op) {
2988 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002989 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002990 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002991 if (builder.isMatrixType(typeId))
2992 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2993 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002994 unaryOp = spv::OpSNegate;
2995 break;
2996
2997 case glslang::EOpLogicalNot:
2998 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002999 unaryOp = spv::OpLogicalNot;
3000 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003001 case glslang::EOpBitwiseNot:
3002 unaryOp = spv::OpNot;
3003 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003004
John Kessenich140f3df2015-06-26 16:58:36 -06003005 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpTranspose:
3012 unaryOp = spv::OpTranspose;
3013 break;
3014
3015 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003031 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 break;
3033 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003034 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 break;
3036 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003037 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003038 break;
3039
3040 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003053 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003054 break;
3055 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058
3059 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003060 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003061 break;
3062 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003063 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003064 break;
3065
3066 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003067 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003068 break;
3069 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003070 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003071 break;
3072 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003073 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 break;
3075 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003076 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003077 break;
3078 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003079 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003080 break;
3081 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003082 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003083 break;
3084
3085 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003089 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 break;
3100 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003101 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003102 break;
3103
3104 case glslang::EOpIsNan:
3105 unaryOp = spv::OpIsNan;
3106 break;
3107 case glslang::EOpIsInf:
3108 unaryOp = spv::OpIsInf;
3109 break;
3110
Rex Xucbc426e2015-12-15 16:03:10 +08003111 case glslang::EOpFloatBitsToInt:
3112 case glslang::EOpFloatBitsToUint:
3113 case glslang::EOpIntBitsToFloat:
3114 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003115 case glslang::EOpDoubleBitsToInt64:
3116 case glslang::EOpDoubleBitsToUint64:
3117 case glslang::EOpInt64BitsToDouble:
3118 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003119 unaryOp = spv::OpBitcast;
3120 break;
3121
John Kessenich140f3df2015-06-26 16:58:36 -06003122 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003135 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003136 break;
3137 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003138 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003139 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003140 case glslang::EOpPackSnorm4x8:
3141 libCall = spv::GLSLstd450PackSnorm4x8;
3142 break;
3143 case glslang::EOpUnpackSnorm4x8:
3144 libCall = spv::GLSLstd450UnpackSnorm4x8;
3145 break;
3146 case glslang::EOpPackUnorm4x8:
3147 libCall = spv::GLSLstd450PackUnorm4x8;
3148 break;
3149 case glslang::EOpUnpackUnorm4x8:
3150 libCall = spv::GLSLstd450UnpackUnorm4x8;
3151 break;
3152 case glslang::EOpPackDouble2x32:
3153 libCall = spv::GLSLstd450PackDouble2x32;
3154 break;
3155 case glslang::EOpUnpackDouble2x32:
3156 libCall = spv::GLSLstd450UnpackDouble2x32;
3157 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003158
Rex Xu8ff43de2016-04-22 16:51:45 +08003159 case glslang::EOpPackInt2x32:
3160 case glslang::EOpUnpackInt2x32:
3161 case glslang::EOpPackUint2x32:
3162 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003163 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003164 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3165 break;
3166
John Kessenich140f3df2015-06-26 16:58:36 -06003167 case glslang::EOpDPdx:
3168 unaryOp = spv::OpDPdx;
3169 break;
3170 case glslang::EOpDPdy:
3171 unaryOp = spv::OpDPdy;
3172 break;
3173 case glslang::EOpFwidth:
3174 unaryOp = spv::OpFwidth;
3175 break;
3176 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003177 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003178 unaryOp = spv::OpDPdxFine;
3179 break;
3180 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003181 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003182 unaryOp = spv::OpDPdyFine;
3183 break;
3184 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003185 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003186 unaryOp = spv::OpFwidthFine;
3187 break;
3188 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003189 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003190 unaryOp = spv::OpDPdxCoarse;
3191 break;
3192 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003193 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003194 unaryOp = spv::OpDPdyCoarse;
3195 break;
3196 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003197 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003198 unaryOp = spv::OpFwidthCoarse;
3199 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003200 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003201 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003202 libCall = spv::GLSLstd450InterpolateAtCentroid;
3203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003204 case glslang::EOpAny:
3205 unaryOp = spv::OpAny;
3206 break;
3207 case glslang::EOpAll:
3208 unaryOp = spv::OpAll;
3209 break;
3210
3211 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003212 if (isFloat)
3213 libCall = spv::GLSLstd450FAbs;
3214 else
3215 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003216 break;
3217 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003218 if (isFloat)
3219 libCall = spv::GLSLstd450FSign;
3220 else
3221 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 break;
3223
John Kessenichfc51d282015-08-19 13:34:18 -06003224 case glslang::EOpAtomicCounterIncrement:
3225 case glslang::EOpAtomicCounterDecrement:
3226 case glslang::EOpAtomicCounter:
3227 {
3228 // Handle all of the atomics in one place, in createAtomicOperation()
3229 std::vector<spv::Id> operands;
3230 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003231 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003232 }
3233
John Kessenichfc51d282015-08-19 13:34:18 -06003234 case glslang::EOpBitFieldReverse:
3235 unaryOp = spv::OpBitReverse;
3236 break;
3237 case glslang::EOpBitCount:
3238 unaryOp = spv::OpBitCount;
3239 break;
3240 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003241 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003242 break;
3243 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003244 if (isUnsigned)
3245 libCall = spv::GLSLstd450FindUMsb;
3246 else
3247 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003248 break;
3249
Rex Xu574ab042016-04-14 16:53:07 +08003250 case glslang::EOpBallot:
3251 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003252 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003253 libCall = spv::GLSLstd450Bad;
3254 break;
3255
Rex Xu338b1852016-05-05 20:38:33 +08003256 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003257 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003258 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003259 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003260
John Kessenich140f3df2015-06-26 16:58:36 -06003261 default:
3262 return 0;
3263 }
3264
3265 spv::Id id;
3266 if (libCall >= 0) {
3267 std::vector<spv::Id> args;
3268 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003269 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003270 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003271 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003272 }
John Kessenich140f3df2015-06-26 16:58:36 -06003273
John Kessenich32cfd492016-02-02 12:37:46 -07003274 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003275}
3276
John Kessenich7a53f762016-01-20 11:19:27 -07003277// Create a unary operation on a matrix
3278spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3279{
3280 // Handle unary operations vector by vector.
3281 // The result type is the same type as the original type.
3282 // The algorithm is to:
3283 // - break the matrix into vectors
3284 // - apply the operation to each vector
3285 // - make a matrix out the vector results
3286
3287 // get the types sorted out
3288 int numCols = builder.getNumColumns(operand);
3289 int numRows = builder.getNumRows(operand);
3290 spv::Id scalarType = builder.getScalarTypeId(typeId);
3291 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3292 std::vector<spv::Id> results;
3293
3294 // do each vector op
3295 for (int c = 0; c < numCols; ++c) {
3296 std::vector<unsigned int> indexes;
3297 indexes.push_back(c);
3298 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3299 results.push_back(builder.createUnaryOp(op, vecType, vec));
3300 builder.setPrecision(results.back(), precision);
3301 }
3302
3303 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003304 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003305}
3306
John Kessenich140f3df2015-06-26 16:58:36 -06003307spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3308{
3309 spv::Op convOp = spv::OpNop;
3310 spv::Id zero = 0;
3311 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003312 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003313
3314 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3315
3316 switch (op) {
3317 case glslang::EOpConvIntToBool:
3318 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003319 case glslang::EOpConvInt64ToBool:
3320 case glslang::EOpConvUint64ToBool:
3321 zero = (op == glslang::EOpConvInt64ToBool ||
3322 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003323 zero = makeSmearedConstant(zero, vectorSize);
3324 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3325
3326 case glslang::EOpConvFloatToBool:
3327 zero = builder.makeFloatConstant(0.0F);
3328 zero = makeSmearedConstant(zero, vectorSize);
3329 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3330
3331 case glslang::EOpConvDoubleToBool:
3332 zero = builder.makeDoubleConstant(0.0);
3333 zero = makeSmearedConstant(zero, vectorSize);
3334 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3335
3336 case glslang::EOpConvBoolToFloat:
3337 convOp = spv::OpSelect;
3338 zero = builder.makeFloatConstant(0.0);
3339 one = builder.makeFloatConstant(1.0);
3340 break;
3341 case glslang::EOpConvBoolToDouble:
3342 convOp = spv::OpSelect;
3343 zero = builder.makeDoubleConstant(0.0);
3344 one = builder.makeDoubleConstant(1.0);
3345 break;
3346 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003347 case glslang::EOpConvBoolToInt64:
3348 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3349 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003350 convOp = spv::OpSelect;
3351 break;
3352 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003353 case glslang::EOpConvBoolToUint64:
3354 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3355 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003356 convOp = spv::OpSelect;
3357 break;
3358
3359 case glslang::EOpConvIntToFloat:
3360 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003361 case glslang::EOpConvInt64ToFloat:
3362 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003363 convOp = spv::OpConvertSToF;
3364 break;
3365
3366 case glslang::EOpConvUintToFloat:
3367 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003368 case glslang::EOpConvUint64ToFloat:
3369 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003370 convOp = spv::OpConvertUToF;
3371 break;
3372
3373 case glslang::EOpConvDoubleToFloat:
3374 case glslang::EOpConvFloatToDouble:
3375 convOp = spv::OpFConvert;
3376 break;
3377
3378 case glslang::EOpConvFloatToInt:
3379 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003380 case glslang::EOpConvFloatToInt64:
3381 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003382 convOp = spv::OpConvertFToS;
3383 break;
3384
3385 case glslang::EOpConvUintToInt:
3386 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003387 case glslang::EOpConvUint64ToInt64:
3388 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003389 if (builder.isInSpecConstCodeGenMode()) {
3390 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003391 zero = (op == glslang::EOpConvUintToInt64 ||
3392 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003393 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003394 // Use OpIAdd, instead of OpBitcast to do the conversion when
3395 // generating for OpSpecConstantOp instruction.
3396 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3397 }
3398 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003399 convOp = spv::OpBitcast;
3400 break;
3401
3402 case glslang::EOpConvFloatToUint:
3403 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003404 case glslang::EOpConvFloatToUint64:
3405 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003406 convOp = spv::OpConvertFToU;
3407 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003408
3409 case glslang::EOpConvIntToInt64:
3410 case glslang::EOpConvInt64ToInt:
3411 convOp = spv::OpSConvert;
3412 break;
3413
3414 case glslang::EOpConvUintToUint64:
3415 case glslang::EOpConvUint64ToUint:
3416 convOp = spv::OpUConvert;
3417 break;
3418
3419 case glslang::EOpConvIntToUint64:
3420 case glslang::EOpConvInt64ToUint:
3421 case glslang::EOpConvUint64ToInt:
3422 case glslang::EOpConvUintToInt64:
3423 // OpSConvert/OpUConvert + OpBitCast
3424 switch (op) {
3425 case glslang::EOpConvIntToUint64:
3426 convOp = spv::OpSConvert;
3427 type = builder.makeIntType(64);
3428 break;
3429 case glslang::EOpConvInt64ToUint:
3430 convOp = spv::OpSConvert;
3431 type = builder.makeIntType(32);
3432 break;
3433 case glslang::EOpConvUint64ToInt:
3434 convOp = spv::OpUConvert;
3435 type = builder.makeUintType(32);
3436 break;
3437 case glslang::EOpConvUintToInt64:
3438 convOp = spv::OpUConvert;
3439 type = builder.makeUintType(64);
3440 break;
3441 default:
3442 assert(0);
3443 break;
3444 }
3445
3446 if (vectorSize > 0)
3447 type = builder.makeVectorType(type, vectorSize);
3448
3449 operand = builder.createUnaryOp(convOp, type, operand);
3450
3451 if (builder.isInSpecConstCodeGenMode()) {
3452 // Build zero scalar or vector for OpIAdd.
3453 zero = (op == glslang::EOpConvIntToUint64 ||
3454 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3455 zero = makeSmearedConstant(zero, vectorSize);
3456 // Use OpIAdd, instead of OpBitcast to do the conversion when
3457 // generating for OpSpecConstantOp instruction.
3458 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3459 }
3460 // For normal run-time conversion instruction, use OpBitcast.
3461 convOp = spv::OpBitcast;
3462 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 default:
3464 break;
3465 }
3466
3467 spv::Id result = 0;
3468 if (convOp == spv::OpNop)
3469 return result;
3470
3471 if (convOp == spv::OpSelect) {
3472 zero = makeSmearedConstant(zero, vectorSize);
3473 one = makeSmearedConstant(one, vectorSize);
3474 result = builder.createTriOp(convOp, destType, operand, one, zero);
3475 } else
3476 result = builder.createUnaryOp(convOp, destType, operand);
3477
John Kessenich32cfd492016-02-02 12:37:46 -07003478 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003479}
3480
3481spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3482{
3483 if (vectorSize == 0)
3484 return constant;
3485
3486 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3487 std::vector<spv::Id> components;
3488 for (int c = 0; c < vectorSize; ++c)
3489 components.push_back(constant);
3490 return builder.makeCompositeConstant(vectorTypeId, components);
3491}
3492
John Kessenich426394d2015-07-23 10:22:48 -06003493// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003494spv::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 -06003495{
3496 spv::Op opCode = spv::OpNop;
3497
3498 switch (op) {
3499 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003500 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003501 opCode = spv::OpAtomicIAdd;
3502 break;
3503 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003504 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003505 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003506 break;
3507 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003508 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003509 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003510 break;
3511 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003512 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003513 opCode = spv::OpAtomicAnd;
3514 break;
3515 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003516 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003517 opCode = spv::OpAtomicOr;
3518 break;
3519 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003520 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003521 opCode = spv::OpAtomicXor;
3522 break;
3523 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003524 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003525 opCode = spv::OpAtomicExchange;
3526 break;
3527 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003528 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003529 opCode = spv::OpAtomicCompareExchange;
3530 break;
3531 case glslang::EOpAtomicCounterIncrement:
3532 opCode = spv::OpAtomicIIncrement;
3533 break;
3534 case glslang::EOpAtomicCounterDecrement:
3535 opCode = spv::OpAtomicIDecrement;
3536 break;
3537 case glslang::EOpAtomicCounter:
3538 opCode = spv::OpAtomicLoad;
3539 break;
3540 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003541 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003542 break;
3543 }
3544
3545 // Sort out the operands
3546 // - mapping from glslang -> SPV
3547 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003548 // - compare-exchange swaps the value and comparator
3549 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003550 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3551 auto opIt = operands.begin(); // walk the glslang operands
3552 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003553 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3554 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3555 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003556 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3557 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003558 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003559 spvAtomicOperands.push_back(*(opIt + 1));
3560 spvAtomicOperands.push_back(*opIt);
3561 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003562 }
John Kessenich426394d2015-07-23 10:22:48 -06003563
John Kessenich3e60a6f2015-09-14 22:45:16 -06003564 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003565 for (; opIt != operands.end(); ++opIt)
3566 spvAtomicOperands.push_back(*opIt);
3567
3568 return builder.createOp(opCode, typeId, spvAtomicOperands);
3569}
3570
John Kessenich91cef522016-05-05 16:45:40 -06003571// Create group invocation operations.
3572spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3573{
3574 builder.addCapability(spv::CapabilityGroups);
3575
3576 std::vector<spv::Id> operands;
3577 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3578 operands.push_back(operand);
3579
3580 switch (op) {
3581 case glslang::EOpAnyInvocation:
3582 case glslang::EOpAllInvocations:
3583 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3584
3585 case glslang::EOpAllInvocationsEqual:
3586 {
3587 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3588 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3589
3590 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3591 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3592 }
3593 default:
3594 logger->missingFunctionality("invocation operation");
3595 return spv::NoResult;
3596 }
3597}
3598
John Kessenich5e4b1242015-08-06 22:53:06 -06003599spv::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 -06003600{
Rex Xu8ff43de2016-04-22 16:51:45 +08003601 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003602 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3603
John Kessenich140f3df2015-06-26 16:58:36 -06003604 spv::Op opCode = spv::OpNop;
3605 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003606 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003607 spv::Id typeId0 = 0;
3608 if (consumedOperands > 0)
3609 typeId0 = builder.getTypeId(operands[0]);
3610 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003611
3612 switch (op) {
3613 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003614 if (isFloat)
3615 libCall = spv::GLSLstd450FMin;
3616 else if (isUnsigned)
3617 libCall = spv::GLSLstd450UMin;
3618 else
3619 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003620 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003621 break;
3622 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003623 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003624 break;
3625 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003626 if (isFloat)
3627 libCall = spv::GLSLstd450FMax;
3628 else if (isUnsigned)
3629 libCall = spv::GLSLstd450UMax;
3630 else
3631 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003632 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003633 break;
3634 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003636 break;
3637 case glslang::EOpDot:
3638 opCode = spv::OpDot;
3639 break;
3640 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003641 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003642 break;
3643
3644 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003645 if (isFloat)
3646 libCall = spv::GLSLstd450FClamp;
3647 else if (isUnsigned)
3648 libCall = spv::GLSLstd450UClamp;
3649 else
3650 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003651 builder.promoteScalar(precision, operands.front(), operands[1]);
3652 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003653 break;
3654 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003655 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3656 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003657 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003658 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003659 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003660 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003661 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003662 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003663 break;
3664 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003665 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003666 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003667 break;
3668 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003669 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003670 builder.promoteScalar(precision, operands[0], operands[2]);
3671 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003672 break;
3673
3674 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003675 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003676 break;
3677 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003678 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003679 break;
3680 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003681 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003682 break;
3683 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003684 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003685 break;
3686 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003687 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003689 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003690 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003691 libCall = spv::GLSLstd450InterpolateAtSample;
3692 break;
3693 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003694 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003695 libCall = spv::GLSLstd450InterpolateAtOffset;
3696 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003697 case glslang::EOpAddCarry:
3698 opCode = spv::OpIAddCarry;
3699 typeId = builder.makeStructResultType(typeId0, typeId0);
3700 consumedOperands = 2;
3701 break;
3702 case glslang::EOpSubBorrow:
3703 opCode = spv::OpISubBorrow;
3704 typeId = builder.makeStructResultType(typeId0, typeId0);
3705 consumedOperands = 2;
3706 break;
3707 case glslang::EOpUMulExtended:
3708 opCode = spv::OpUMulExtended;
3709 typeId = builder.makeStructResultType(typeId0, typeId0);
3710 consumedOperands = 2;
3711 break;
3712 case glslang::EOpIMulExtended:
3713 opCode = spv::OpSMulExtended;
3714 typeId = builder.makeStructResultType(typeId0, typeId0);
3715 consumedOperands = 2;
3716 break;
3717 case glslang::EOpBitfieldExtract:
3718 if (isUnsigned)
3719 opCode = spv::OpBitFieldUExtract;
3720 else
3721 opCode = spv::OpBitFieldSExtract;
3722 break;
3723 case glslang::EOpBitfieldInsert:
3724 opCode = spv::OpBitFieldInsert;
3725 break;
3726
3727 case glslang::EOpFma:
3728 libCall = spv::GLSLstd450Fma;
3729 break;
3730 case glslang::EOpFrexp:
3731 libCall = spv::GLSLstd450FrexpStruct;
3732 if (builder.getNumComponents(operands[0]) == 1)
3733 frexpIntType = builder.makeIntegerType(32, true);
3734 else
3735 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3736 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3737 consumedOperands = 1;
3738 break;
3739 case glslang::EOpLdexp:
3740 libCall = spv::GLSLstd450Ldexp;
3741 break;
3742
Rex Xu574ab042016-04-14 16:53:07 +08003743 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003744 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003745 libCall = spv::GLSLstd450Bad;
3746 break;
3747
John Kessenich140f3df2015-06-26 16:58:36 -06003748 default:
3749 return 0;
3750 }
3751
3752 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003753 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003754 // Use an extended instruction from the standard library.
3755 // Construct the call arguments, without modifying the original operands vector.
3756 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3757 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003758 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003759 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003760 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003761 case 0:
3762 // should all be handled by visitAggregate and createNoArgOperation
3763 assert(0);
3764 return 0;
3765 case 1:
3766 // should all be handled by createUnaryOperation
3767 assert(0);
3768 return 0;
3769 case 2:
3770 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3771 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003773 // anything 3 or over doesn't have l-value operands, so all should be consumed
3774 assert(consumedOperands == operands.size());
3775 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003776 break;
3777 }
3778 }
3779
John Kessenich55e7d112015-11-15 21:33:39 -07003780 // Decode the return types that were structures
3781 switch (op) {
3782 case glslang::EOpAddCarry:
3783 case glslang::EOpSubBorrow:
3784 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3785 id = builder.createCompositeExtract(id, typeId0, 0);
3786 break;
3787 case glslang::EOpUMulExtended:
3788 case glslang::EOpIMulExtended:
3789 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3790 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3791 break;
3792 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003793 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003794 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3795 id = builder.createCompositeExtract(id, typeId0, 0);
3796 break;
3797 default:
3798 break;
3799 }
3800
John Kessenich32cfd492016-02-02 12:37:46 -07003801 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003802}
3803
3804// Intrinsics with no arguments, no return value, and no precision.
3805spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3806{
3807 // TODO: get the barrier operands correct
3808
3809 switch (op) {
3810 case glslang::EOpEmitVertex:
3811 builder.createNoResultOp(spv::OpEmitVertex);
3812 return 0;
3813 case glslang::EOpEndPrimitive:
3814 builder.createNoResultOp(spv::OpEndPrimitive);
3815 return 0;
3816 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3818 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003819 return 0;
3820 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003822 return 0;
3823 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003824 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003825 return 0;
3826 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003827 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003828 return 0;
3829 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003830 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003831 return 0;
3832 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003833 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003834 return 0;
3835 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003836 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003837 return 0;
3838 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003839 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003840 return 0;
3841 }
3842}
3843
3844spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3845{
John Kessenich2f273362015-07-18 22:34:27 -06003846 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003847 spv::Id id;
3848 if (symbolValues.end() != iter) {
3849 id = iter->second;
3850 return id;
3851 }
3852
3853 // it was not found, create it
3854 id = createSpvVariable(symbol);
3855 symbolValues[symbol->getId()] = id;
3856
3857 if (! symbol->getType().isStruct()) {
3858 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003859 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003860 if (symbol->getType().getQualifier().hasSpecConstantId())
3861 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003862 if (symbol->getQualifier().hasLocation())
3863 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3864 if (symbol->getQualifier().hasIndex())
3865 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3866 if (symbol->getQualifier().hasComponent())
3867 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3868 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003869 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003870 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003871 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003872 if (symbol->getQualifier().hasXfbBuffer())
3873 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3874 if (symbol->getQualifier().hasXfbOffset())
3875 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3876 }
3877 }
3878
John Kesseniche0b6cad2015-12-24 10:30:13 -07003879 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003880 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003881 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003882 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003883 }
John Kessenich140f3df2015-06-26 16:58:36 -06003884 if (symbol->getQualifier().hasSet())
3885 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003886 else if (IsDescriptorResource(symbol->getType())) {
3887 // default to 0
3888 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3889 }
John Kessenich140f3df2015-06-26 16:58:36 -06003890 if (symbol->getQualifier().hasBinding())
3891 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003892 if (symbol->getQualifier().hasAttachment())
3893 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003894 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003895 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003897 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003898 if (symbol->getQualifier().hasXfbBuffer())
3899 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3900 }
3901
Rex Xu1da878f2016-02-21 20:59:01 +08003902 if (symbol->getType().isImage()) {
3903 std::vector<spv::Decoration> memory;
3904 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3905 for (unsigned int i = 0; i < memory.size(); ++i)
3906 addDecoration(id, memory[i]);
3907 }
3908
John Kessenich140f3df2015-06-26 16:58:36 -06003909 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003910 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003912 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003913
John Kessenich140f3df2015-06-26 16:58:36 -06003914 return id;
3915}
3916
John Kessenich55e7d112015-11-15 21:33:39 -07003917// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003918void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3919{
3920 if (dec != spv::BadValue)
3921 builder.addDecoration(id, dec);
3922}
3923
John Kessenich55e7d112015-11-15 21:33:39 -07003924// If 'dec' is valid, add a one-operand decoration to an object
3925void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3926{
3927 if (dec != spv::BadValue)
3928 builder.addDecoration(id, dec, value);
3929}
3930
3931// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003932void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3933{
3934 if (dec != spv::BadValue)
3935 builder.addMemberDecoration(id, (unsigned)member, dec);
3936}
3937
John Kessenich92187592016-02-01 13:45:25 -07003938// If 'dec' is valid, add a one-operand decoration to a struct member
3939void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3940{
3941 if (dec != spv::BadValue)
3942 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3943}
3944
John Kessenich55e7d112015-11-15 21:33:39 -07003945// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003946// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003947//
3948// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3949//
3950// Recursively walk the nodes. The nodes form a tree whose leaves are
3951// regular constants, which themselves are trees that createSpvConstant()
3952// recursively walks. So, this function walks the "top" of the tree:
3953// - emit specialization constant-building instructions for specConstant
3954// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003955spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003956{
John Kessenich7cc0e282016-03-20 00:46:02 -06003957 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003958
qining4f4bb812016-04-03 23:55:17 -04003959 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003960 if (! node.getQualifier().specConstant) {
3961 // hand off to the non-spec-constant path
3962 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3963 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003964 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003965 nextConst, false);
3966 }
3967
3968 // We now know we have a specialization constant to build
3969
qining4f4bb812016-04-03 23:55:17 -04003970 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3971 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3972 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3973 std::vector<spv::Id> dimConstId;
3974 for (int dim = 0; dim < 3; ++dim) {
3975 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3976 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3977 if (specConst)
3978 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3979 }
3980 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3981 }
3982
3983 // An AST node labelled as specialization constant should be a symbol node.
3984 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3985 if (auto* sn = node.getAsSymbolNode()) {
3986 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04003987 // Traverse the constant constructor sub tree like generating normal run-time instructions.
3988 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
3989 // will set the builder into spec constant op instruction generating mode.
3990 sub_tree->traverse(this);
3991 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04003992 } else if (auto* const_union_array = &sn->getConstArray()){
3993 int nextConst = 0;
3994 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003995 }
3996 }
qining4f4bb812016-04-03 23:55:17 -04003997
3998 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3999 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004000 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004001 exit(1);
4002 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004003}
4004
John Kessenich140f3df2015-06-26 16:58:36 -06004005// Use 'consts' as the flattened glslang source of scalar constants to recursively
4006// build the aggregate SPIR-V constant.
4007//
4008// If there are not enough elements present in 'consts', 0 will be substituted;
4009// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4010//
qining08408382016-03-21 09:51:37 -04004011spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004012{
4013 // vector of constants for SPIR-V
4014 std::vector<spv::Id> spvConsts;
4015
4016 // Type is used for struct and array constants
4017 spv::Id typeId = convertGlslangToSpvType(glslangType);
4018
4019 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004020 glslang::TType elementType(glslangType, 0);
4021 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004022 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004023 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004024 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004025 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004026 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004027 } else if (glslangType.getStruct()) {
4028 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4029 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004030 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004031 } else if (glslangType.isVector()) {
4032 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4033 bool zero = nextConst >= consts.size();
4034 switch (glslangType.getBasicType()) {
4035 case glslang::EbtInt:
4036 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4037 break;
4038 case glslang::EbtUint:
4039 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4040 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004041 case glslang::EbtInt64:
4042 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4043 break;
4044 case glslang::EbtUint64:
4045 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4046 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 case glslang::EbtFloat:
4048 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4049 break;
4050 case glslang::EbtDouble:
4051 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4052 break;
4053 case glslang::EbtBool:
4054 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4055 break;
4056 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004057 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004058 break;
4059 }
4060 ++nextConst;
4061 }
4062 } else {
4063 // we have a non-aggregate (scalar) constant
4064 bool zero = nextConst >= consts.size();
4065 spv::Id scalar = 0;
4066 switch (glslangType.getBasicType()) {
4067 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004068 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004071 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004073 case glslang::EbtInt64:
4074 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4075 break;
4076 case glslang::EbtUint64:
4077 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4078 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004080 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004083 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004084 break;
4085 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004086 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004087 break;
4088 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004089 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004090 break;
4091 }
4092 ++nextConst;
4093 return scalar;
4094 }
4095
4096 return builder.makeCompositeConstant(typeId, spvConsts);
4097}
4098
John Kessenich7c1aa102015-10-15 13:29:11 -06004099// Return true if the node is a constant or symbol whose reading has no
4100// non-trivial observable cost or effect.
4101bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4102{
4103 // don't know what this is
4104 if (node == nullptr)
4105 return false;
4106
4107 // a constant is safe
4108 if (node->getAsConstantUnion() != nullptr)
4109 return true;
4110
4111 // not a symbol means non-trivial
4112 if (node->getAsSymbolNode() == nullptr)
4113 return false;
4114
4115 // a symbol, depends on what's being read
4116 switch (node->getType().getQualifier().storage) {
4117 case glslang::EvqTemporary:
4118 case glslang::EvqGlobal:
4119 case glslang::EvqIn:
4120 case glslang::EvqInOut:
4121 case glslang::EvqConst:
4122 case glslang::EvqConstReadOnly:
4123 case glslang::EvqUniform:
4124 return true;
4125 default:
4126 return false;
4127 }
4128}
4129
4130// A node is trivial if it is a single operation with no side effects.
4131// Error on the side of saying non-trivial.
4132// Return true if trivial.
4133bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4134{
4135 if (node == nullptr)
4136 return false;
4137
4138 // symbols and constants are trivial
4139 if (isTrivialLeaf(node))
4140 return true;
4141
4142 // otherwise, it needs to be a simple operation or one or two leaf nodes
4143
4144 // not a simple operation
4145 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4146 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4147 if (binaryNode == nullptr && unaryNode == nullptr)
4148 return false;
4149
4150 // not on leaf nodes
4151 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4152 return false;
4153
4154 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4155 return false;
4156 }
4157
4158 switch (node->getAsOperator()->getOp()) {
4159 case glslang::EOpLogicalNot:
4160 case glslang::EOpConvIntToBool:
4161 case glslang::EOpConvUintToBool:
4162 case glslang::EOpConvFloatToBool:
4163 case glslang::EOpConvDoubleToBool:
4164 case glslang::EOpEqual:
4165 case glslang::EOpNotEqual:
4166 case glslang::EOpLessThan:
4167 case glslang::EOpGreaterThan:
4168 case glslang::EOpLessThanEqual:
4169 case glslang::EOpGreaterThanEqual:
4170 case glslang::EOpIndexDirect:
4171 case glslang::EOpIndexDirectStruct:
4172 case glslang::EOpLogicalXor:
4173 case glslang::EOpAny:
4174 case glslang::EOpAll:
4175 return true;
4176 default:
4177 return false;
4178 }
4179}
4180
4181// Emit short-circuiting code, where 'right' is never evaluated unless
4182// the left side is true (for &&) or false (for ||).
4183spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4184{
4185 spv::Id boolTypeId = builder.makeBoolType();
4186
4187 // emit left operand
4188 builder.clearAccessChain();
4189 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004190 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004191
4192 // Operands to accumulate OpPhi operands
4193 std::vector<spv::Id> phiOperands;
4194 // accumulate left operand's phi information
4195 phiOperands.push_back(leftId);
4196 phiOperands.push_back(builder.getBuildPoint()->getId());
4197
4198 // Make the two kinds of operation symmetric with a "!"
4199 // || => emit "if (! left) result = right"
4200 // && => emit "if ( left) result = right"
4201 //
4202 // TODO: this runtime "not" for || could be avoided by adding functionality
4203 // to 'builder' to have an "else" without an "then"
4204 if (op == glslang::EOpLogicalOr)
4205 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4206
4207 // make an "if" based on the left value
4208 spv::Builder::If ifBuilder(leftId, builder);
4209
4210 // emit right operand as the "then" part of the "if"
4211 builder.clearAccessChain();
4212 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004213 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004214
4215 // accumulate left operand's phi information
4216 phiOperands.push_back(rightId);
4217 phiOperands.push_back(builder.getBuildPoint()->getId());
4218
4219 // finish the "if"
4220 ifBuilder.makeEndIf();
4221
4222 // phi together the two results
4223 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4224}
4225
John Kessenich140f3df2015-06-26 16:58:36 -06004226}; // end anonymous namespace
4227
4228namespace glslang {
4229
John Kessenich68d78fd2015-07-12 19:28:10 -06004230void GetSpirvVersion(std::string& version)
4231{
John Kessenich9e55f632015-07-15 10:03:39 -06004232 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004233 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004234 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004235 version = buf;
4236}
4237
John Kessenich140f3df2015-06-26 16:58:36 -06004238// Write SPIR-V out to a binary file
4239void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4240{
4241 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004242 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004243 for (int i = 0; i < (int)spirv.size(); ++i) {
4244 unsigned int word = spirv[i];
4245 out.write((const char*)&word, 4);
4246 }
4247 out.close();
4248}
4249
4250//
4251// Set up the glslang traversal
4252//
4253void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4254{
Lei Zhang17535f72016-05-04 15:55:59 -04004255 spv::SpvBuildLogger logger;
4256 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004257}
4258
Lei Zhang17535f72016-05-04 15:55:59 -04004259void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004260{
John Kessenich140f3df2015-06-26 16:58:36 -06004261 TIntermNode* root = intermediate.getTreeRoot();
4262
4263 if (root == 0)
4264 return;
4265
4266 glslang::GetThreadPoolAllocator().push();
4267
Lei Zhang17535f72016-05-04 15:55:59 -04004268 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004269
4270 root->traverse(&it);
4271
4272 it.dumpSpv(spirv);
4273
4274 glslang::GetThreadPoolAllocator().pop();
4275}
4276
4277}; // end namespace glslang