blob: d160e36e5035c2e5c283f80bb495ca979f9642e3 [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
qining9220dbb2016-05-04 17:34:38 -0400388// If glslang type is noContraction, return SPIR-V NoContraction decoration.
389spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
390{
391 if (qualifier.noContraction)
392 return spv::DecorationNoContraction;
393 else
394 return (spv::Decoration)spv::BadValue;
395}
396
John Kessenich140f3df2015-06-26 16:58:36 -0600397// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700398spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600399{
400 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700401 case glslang::EbvPointSize:
402 switch (glslangIntermediate->getStage()) {
403 case EShLangGeometry:
404 builder.addCapability(spv::CapabilityGeometryPointSize);
405 break;
406 case EShLangTessControl:
407 case EShLangTessEvaluation:
408 builder.addCapability(spv::CapabilityTessellationPointSize);
409 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100410 default:
411 break;
John Kessenich92187592016-02-01 13:45:25 -0700412 }
413 return spv::BuiltInPointSize;
414
415 case glslang::EbvClipDistance:
416 builder.addCapability(spv::CapabilityClipDistance);
417 return spv::BuiltInClipDistance;
418
419 case glslang::EbvCullDistance:
420 builder.addCapability(spv::CapabilityCullDistance);
421 return spv::BuiltInCullDistance;
422
423 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500424 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700425 return spv::BuiltInViewportIndex;
426
John Kessenich5e801132016-02-15 11:09:46 -0700427 case glslang::EbvSampleId:
428 builder.addCapability(spv::CapabilitySampleRateShading);
429 return spv::BuiltInSampleId;
430
431 case glslang::EbvSamplePosition:
432 builder.addCapability(spv::CapabilitySampleRateShading);
433 return spv::BuiltInSamplePosition;
434
435 case glslang::EbvSampleMask:
436 builder.addCapability(spv::CapabilitySampleRateShading);
437 return spv::BuiltInSampleMask;
438
John Kessenich140f3df2015-06-26 16:58:36 -0600439 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600440 case glslang::EbvVertexId: return spv::BuiltInVertexId;
441 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700442 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
443 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600444 case glslang::EbvBaseVertex:
445 case glslang::EbvBaseInstance:
446 case glslang::EbvDrawId:
447 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600448 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600449 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600450 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
451 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
452 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600453 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
454 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
455 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
456 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
457 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
458 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
459 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600460 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
461 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
462 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
463 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
464 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
465 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
466 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
467 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800468 case glslang::EbvSubGroupSize:
469 case glslang::EbvSubGroupInvocation:
470 case glslang::EbvSubGroupEqMask:
471 case glslang::EbvSubGroupGeMask:
472 case glslang::EbvSubGroupGtMask:
473 case glslang::EbvSubGroupLeMask:
474 case glslang::EbvSubGroupLtMask:
475 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600476 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800477 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600478 default: return (spv::BuiltIn)spv::BadValue;
479 }
480}
481
Rex Xufc618912015-09-09 16:42:49 +0800482// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700483spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800484{
485 assert(type.getBasicType() == glslang::EbtSampler);
486
John Kessenich5d0fa972016-02-15 11:57:00 -0700487 // Check for capabilities
488 switch (type.getQualifier().layoutFormat) {
489 case glslang::ElfRg32f:
490 case glslang::ElfRg16f:
491 case glslang::ElfR11fG11fB10f:
492 case glslang::ElfR16f:
493 case glslang::ElfRgba16:
494 case glslang::ElfRgb10A2:
495 case glslang::ElfRg16:
496 case glslang::ElfRg8:
497 case glslang::ElfR16:
498 case glslang::ElfR8:
499 case glslang::ElfRgba16Snorm:
500 case glslang::ElfRg16Snorm:
501 case glslang::ElfRg8Snorm:
502 case glslang::ElfR16Snorm:
503 case glslang::ElfR8Snorm:
504
505 case glslang::ElfRg32i:
506 case glslang::ElfRg16i:
507 case glslang::ElfRg8i:
508 case glslang::ElfR16i:
509 case glslang::ElfR8i:
510
511 case glslang::ElfRgb10a2ui:
512 case glslang::ElfRg32ui:
513 case glslang::ElfRg16ui:
514 case glslang::ElfRg8ui:
515 case glslang::ElfR16ui:
516 case glslang::ElfR8ui:
517 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
518 break;
519
520 default:
521 break;
522 }
523
524 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800525 switch (type.getQualifier().layoutFormat) {
526 case glslang::ElfNone: return spv::ImageFormatUnknown;
527 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
528 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
529 case glslang::ElfR32f: return spv::ImageFormatR32f;
530 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
531 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
532 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
533 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
534 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
535 case glslang::ElfR16f: return spv::ImageFormatR16f;
536 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
537 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
538 case glslang::ElfRg16: return spv::ImageFormatRg16;
539 case glslang::ElfRg8: return spv::ImageFormatRg8;
540 case glslang::ElfR16: return spv::ImageFormatR16;
541 case glslang::ElfR8: return spv::ImageFormatR8;
542 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
543 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
544 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
545 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
546 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
547 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
548 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
549 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
550 case glslang::ElfR32i: return spv::ImageFormatR32i;
551 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
552 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
553 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
554 case glslang::ElfR16i: return spv::ImageFormatR16i;
555 case glslang::ElfR8i: return spv::ImageFormatR8i;
556 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
557 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
558 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
559 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
560 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
561 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
562 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
563 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
564 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
565 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
566 default: return (spv::ImageFormat)spv::BadValue;
567 }
568}
569
John Kessenich6c292d32016-02-15 20:58:50 -0700570// Return whether or not the given type is something that should be tied to a
571// descriptor set.
572bool IsDescriptorResource(const glslang::TType& type)
573{
John Kessenichf7497e22016-03-08 21:36:22 -0700574 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700575 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700576 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700577
578 // non block...
579 // basically samplerXXX/subpass/sampler/texture are all included
580 // if they are the global-scope-class, not the function parameter
581 // (or local, if they ever exist) class.
582 if (type.getBasicType() == glslang::EbtSampler)
583 return type.getQualifier().isUniformOrBuffer();
584
585 // None of the above.
586 return false;
587}
588
John Kesseniche0b6cad2015-12-24 10:30:13 -0700589void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
590{
591 if (child.layoutMatrix == glslang::ElmNone)
592 child.layoutMatrix = parent.layoutMatrix;
593
594 if (parent.invariant)
595 child.invariant = true;
596 if (parent.nopersp)
597 child.nopersp = true;
598 if (parent.flat)
599 child.flat = true;
600 if (parent.centroid)
601 child.centroid = true;
602 if (parent.patch)
603 child.patch = true;
604 if (parent.sample)
605 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800606 if (parent.coherent)
607 child.coherent = true;
608 if (parent.volatil)
609 child.volatil = true;
610 if (parent.restrict)
611 child.restrict = true;
612 if (parent.readonly)
613 child.readonly = true;
614 if (parent.writeonly)
615 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700616}
617
618bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
619{
John Kessenich7b9fa252016-01-21 18:56:57 -0700620 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700621 // - struct members can inherit from a struct declaration
622 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
623 // - are not part of the offset/st430/etc or row/column-major layout
qining9220dbb2016-05-04 17:34:38 -0400624 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation() ||
625 qualifier.noContraction;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700626}
627
John Kessenich140f3df2015-06-26 16:58:36 -0600628//
629// Implement the TGlslangToSpvTraverser class.
630//
631
Lei Zhang17535f72016-05-04 15:55:59 -0400632TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
633 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
634 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600635 inMain(false), mainTerminated(false), linkageOnly(false),
636 glslangIntermediate(glslangIntermediate)
637{
638 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
639
640 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700641 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600642 stdBuiltins = builder.import("GLSL.std.450");
643 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700644 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
645 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600646
647 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600648 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
649 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600650 builder.addSourceExtension(it->c_str());
651
652 // Add the top-level modes for this shader.
653
John Kessenich92187592016-02-01 13:45:25 -0700654 if (glslangIntermediate->getXfbMode()) {
655 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600656 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700657 }
John Kessenich140f3df2015-06-26 16:58:36 -0600658
659 unsigned int mode;
660 switch (glslangIntermediate->getStage()) {
661 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600662 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600663 break;
664
665 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600666 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600667 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
668 break;
669
670 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600671 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600672 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700673 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
674 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
675 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600676 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600677 }
678 if (mode != spv::BadValue)
679 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
680
John Kesseniche6903322015-10-13 16:29:02 -0600681 switch (glslangIntermediate->getVertexSpacing()) {
682 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
683 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
684 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
685 default: mode = spv::BadValue; break;
686 }
687 if (mode != spv::BadValue)
688 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
689
690 switch (glslangIntermediate->getVertexOrder()) {
691 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
692 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
693 default: mode = spv::BadValue; break;
694 }
695 if (mode != spv::BadValue)
696 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
697
698 if (glslangIntermediate->getPointMode())
699 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600700 break;
701
702 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600703 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600704 switch (glslangIntermediate->getInputPrimitive()) {
705 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
706 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
707 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700708 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600709 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
710 default: mode = spv::BadValue; break;
711 }
712 if (mode != spv::BadValue)
713 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600714
John Kessenich140f3df2015-06-26 16:58:36 -0600715 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
716
717 switch (glslangIntermediate->getOutputPrimitive()) {
718 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
719 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
720 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
721 default: mode = spv::BadValue; break;
722 }
723 if (mode != spv::BadValue)
724 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
725 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
726 break;
727
728 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600729 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600730 if (glslangIntermediate->getPixelCenterInteger())
731 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600732
John Kessenich140f3df2015-06-26 16:58:36 -0600733 if (glslangIntermediate->getOriginUpperLeft())
734 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600735 else
736 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600737
738 if (glslangIntermediate->getEarlyFragmentTests())
739 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
740
741 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600742 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
743 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
744 default: mode = spv::BadValue; break;
745 }
746 if (mode != spv::BadValue)
747 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
748
749 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
750 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600751 break;
752
753 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600754 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600755 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
756 glslangIntermediate->getLocalSize(1),
757 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600758 break;
759
760 default:
761 break;
762 }
763
764}
765
John Kessenich7ba63412015-12-20 17:37:07 -0700766// Finish everything and dump
767void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
768{
769 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100770 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
771 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700772
qiningda397332016-03-09 19:54:03 -0500773 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700774 builder.dump(out);
775}
776
John Kessenich140f3df2015-06-26 16:58:36 -0600777TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
778{
779 if (! mainTerminated) {
780 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
781 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600782 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600783 }
784}
785
786//
787// Implement the traversal functions.
788//
789// Return true from interior nodes to have the external traversal
790// continue on to children. Return false if children were
791// already processed.
792//
793
794//
795// Symbols can turn into
796// - uniform/input reads
797// - output writes
798// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
799// - something simple that degenerates into the last bullet
800//
801void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
802{
qining75d1d802016-04-06 14:42:01 -0400803 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
804 if (symbol->getType().getQualifier().isSpecConstant())
805 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
806
John Kessenich140f3df2015-06-26 16:58:36 -0600807 // getSymbolId() will set up all the IO decorations on the first call.
808 // Formal function parameters were mapped during makeFunctions().
809 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700810
811 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
812 if (builder.isPointer(id)) {
813 spv::StorageClass sc = builder.getStorageClass(id);
814 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
815 iOSet.insert(id);
816 }
817
818 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700819 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600820 // Prepare to generate code for the access
821
822 // L-value chains will be computed left to right. We're on the symbol now,
823 // which is the left-most part of the access chain, so now is "clear" time,
824 // followed by setting the base.
825 builder.clearAccessChain();
826
827 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700828 // except for
829 // A) "const in" arguments to a function, which are an intermediate object.
830 // See comments in handleUserFunctionCall().
831 // B) Specialization constants (normal constant don't even come in as a variable),
832 // These are also pure R-values.
833 glslang::TQualifier qualifier = symbol->getQualifier();
834 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
835 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600836 builder.setAccessChainRValue(id);
837 else
838 builder.setAccessChainLValue(id);
839 }
840}
841
842bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
843{
qining40887662016-04-03 22:20:42 -0400844 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
845 if (node->getType().getQualifier().isSpecConstant())
846 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
847
John Kessenich140f3df2015-06-26 16:58:36 -0600848 // First, handle special cases
849 switch (node->getOp()) {
850 case glslang::EOpAssign:
851 case glslang::EOpAddAssign:
852 case glslang::EOpSubAssign:
853 case glslang::EOpMulAssign:
854 case glslang::EOpVectorTimesMatrixAssign:
855 case glslang::EOpVectorTimesScalarAssign:
856 case glslang::EOpMatrixTimesScalarAssign:
857 case glslang::EOpMatrixTimesMatrixAssign:
858 case glslang::EOpDivAssign:
859 case glslang::EOpModAssign:
860 case glslang::EOpAndAssign:
861 case glslang::EOpInclusiveOrAssign:
862 case glslang::EOpExclusiveOrAssign:
863 case glslang::EOpLeftShiftAssign:
864 case glslang::EOpRightShiftAssign:
865 // A bin-op assign "a += b" means the same thing as "a = a + b"
866 // where a is evaluated before b. For a simple assignment, GLSL
867 // says to evaluate the left before the right. So, always, left
868 // node then right node.
869 {
870 // get the left l-value, save it away
871 builder.clearAccessChain();
872 node->getLeft()->traverse(this);
873 spv::Builder::AccessChain lValue = builder.getAccessChain();
874
875 // evaluate the right
876 builder.clearAccessChain();
877 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700878 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600879
880 if (node->getOp() != glslang::EOpAssign) {
881 // the left is also an r-value
882 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700883 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600884
885 // do the operation
886 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
887 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
888 node->getType().getBasicType());
889
qining9220dbb2016-05-04 17:34:38 -0400890 // Decorate this instruction, if this node has 'noContraction' qualifier.
891 addDecoration(rValue, TranslateNoContractionDecoration(node->getType().getQualifier()));
892
John Kessenich140f3df2015-06-26 16:58:36 -0600893 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700894 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600895 }
896
897 // store the result
898 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800899 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600900
901 // assignments are expressions having an rValue after they are evaluated...
902 builder.clearAccessChain();
903 builder.setAccessChainRValue(rValue);
904 }
905 return false;
906 case glslang::EOpIndexDirect:
907 case glslang::EOpIndexDirectStruct:
908 {
909 // Get the left part of the access chain.
910 node->getLeft()->traverse(this);
911
912 // Add the next element in the chain
913
John Kessenich55e7d112015-11-15 21:33:39 -0700914 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600915 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
916 // This may be, e.g., an anonymous block-member selection, which generally need
917 // index remapping due to hidden members in anonymous blocks.
918 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700919 assert(remapper.size() > 0);
920 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600921 }
922
923 if (! node->getLeft()->getType().isArray() &&
924 node->getLeft()->getType().isVector() &&
925 node->getOp() == glslang::EOpIndexDirect) {
926 // This is essentially a hard-coded vector swizzle of size 1,
927 // so short circuit the access-chain stuff with a swizzle.
928 std::vector<unsigned> swizzle;
929 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600930 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600931 } else {
932 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600933 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600934 }
935 }
936 return false;
937 case glslang::EOpIndexIndirect:
938 {
939 // Structure or array or vector indirection.
940 // Will use native SPIR-V access-chain for struct and array indirection;
941 // matrices are arrays of vectors, so will also work for a matrix.
942 // Will use the access chain's 'component' for variable index into a vector.
943
944 // This adapter is building access chains left to right.
945 // Set up the access chain to the left.
946 node->getLeft()->traverse(this);
947
948 // save it so that computing the right side doesn't trash it
949 spv::Builder::AccessChain partial = builder.getAccessChain();
950
951 // compute the next index in the chain
952 builder.clearAccessChain();
953 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700954 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // restore the saved access chain
957 builder.setAccessChain(partial);
958
959 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600960 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600961 else
John Kessenichfa668da2015-09-13 14:46:30 -0600962 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600963 }
964 return false;
965 case glslang::EOpVectorSwizzle:
966 {
967 node->getLeft()->traverse(this);
968 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
969 std::vector<unsigned> swizzle;
970 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
971 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600972 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600973 }
974 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600975 case glslang::EOpLogicalOr:
976 case glslang::EOpLogicalAnd:
977 {
978
979 // These may require short circuiting, but can sometimes be done as straight
980 // binary operations. The right operand must be short circuited if it has
981 // side effects, and should probably be if it is complex.
982 if (isTrivial(node->getRight()->getAsTyped()))
983 break; // handle below as a normal binary operation
984 // otherwise, we need to do dynamic short circuiting on the right operand
985 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
986 builder.clearAccessChain();
987 builder.setAccessChainRValue(result);
988 }
989 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600990 default:
991 break;
992 }
993
994 // Assume generic binary op...
995
John Kessenich32cfd492016-02-02 12:37:46 -0700996 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600997 builder.clearAccessChain();
998 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700999 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001000
John Kessenich32cfd492016-02-02 12:37:46 -07001001 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001002 builder.clearAccessChain();
1003 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001004 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001005
John Kessenich32cfd492016-02-02 12:37:46 -07001006 // get result
1007 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
1008 convertGlslangToSpvType(node->getType()), left, right,
1009 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001010
John Kessenich50e57562015-12-21 21:21:11 -07001011 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001012 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001013 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001014 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001015 } else {
qining9220dbb2016-05-04 17:34:38 -04001016 // Decorate this instruction, if this node has 'noContraction' qualifier.
1017 addDecoration(result, TranslateNoContractionDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06001018 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001019 return false;
1020 }
John Kessenich140f3df2015-06-26 16:58:36 -06001021}
1022
1023bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1024{
qining40887662016-04-03 22:20:42 -04001025 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1026 if (node->getType().getQualifier().isSpecConstant())
1027 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1028
John Kessenichfc51d282015-08-19 13:34:18 -06001029 spv::Id result = spv::NoResult;
1030
1031 // try texturing first
1032 result = createImageTextureFunctionCall(node);
1033 if (result != spv::NoResult) {
1034 builder.clearAccessChain();
1035 builder.setAccessChainRValue(result);
1036
1037 return false; // done with this node
1038 }
1039
1040 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001041
1042 if (node->getOp() == glslang::EOpArrayLength) {
1043 // Quite special; won't want to evaluate the operand.
1044
1045 // Normal .length() would have been constant folded by the front-end.
1046 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001047 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001048 assert(node->getOperand()->getType().isRuntimeSizedArray());
1049 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1050 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001051 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1052 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001053
1054 builder.clearAccessChain();
1055 builder.setAccessChainRValue(length);
1056
1057 return false;
1058 }
1059
John Kessenichfc51d282015-08-19 13:34:18 -06001060 // Start by evaluating the operand
1061
John Kessenich140f3df2015-06-26 16:58:36 -06001062 builder.clearAccessChain();
1063 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001064
Rex Xufc618912015-09-09 16:42:49 +08001065 spv::Id operand = spv::NoResult;
1066
1067 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1068 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001069 node->getOp() == glslang::EOpAtomicCounter ||
1070 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001071 operand = builder.accessChainGetLValue(); // Special case l-value operands
1072 else
John Kessenich32cfd492016-02-02 12:37:46 -07001073 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001074
1075 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1076
1077 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001078 if (! result)
1079 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001080
1081 // if not, then possibly an operation
1082 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001083 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001084
1085 if (result) {
qining9220dbb2016-05-04 17:34:38 -04001086 // Decorate this instruction, if this node has 'noContraction' qualifier.
1087 addDecoration(result, TranslateNoContractionDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06001088 builder.clearAccessChain();
1089 builder.setAccessChainRValue(result);
1090
1091 return false; // done with this node
1092 }
1093
1094 // it must be a special case, check...
1095 switch (node->getOp()) {
1096 case glslang::EOpPostIncrement:
1097 case glslang::EOpPostDecrement:
1098 case glslang::EOpPreIncrement:
1099 case glslang::EOpPreDecrement:
1100 {
1101 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001102 spv::Id one = 0;
1103 if (node->getBasicType() == glslang::EbtFloat)
1104 one = builder.makeFloatConstant(1.0F);
1105 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1106 one = builder.makeInt64Constant(1);
1107 else
1108 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001109 glslang::TOperator op;
1110 if (node->getOp() == glslang::EOpPreIncrement ||
1111 node->getOp() == glslang::EOpPostIncrement)
1112 op = glslang::EOpAdd;
1113 else
1114 op = glslang::EOpSub;
1115
1116 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001117 convertGlslangToSpvType(node->getType()), operand, one,
1118 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001119 assert(result != spv::NoResult);
qining9220dbb2016-05-04 17:34:38 -04001120 // Decorate this instruction, if this node has 'noContraction' qualifier.
1121 addDecoration(result, TranslateNoContractionDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06001122
1123 // The result of operation is always stored, but conditionally the
1124 // consumed result. The consumed result is always an r-value.
1125 builder.accessChainStore(result);
1126 builder.clearAccessChain();
1127 if (node->getOp() == glslang::EOpPreIncrement ||
1128 node->getOp() == glslang::EOpPreDecrement)
1129 builder.setAccessChainRValue(result);
1130 else
1131 builder.setAccessChainRValue(operand);
1132 }
1133
1134 return false;
1135
1136 case glslang::EOpEmitStreamVertex:
1137 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1138 return false;
1139 case glslang::EOpEndStreamPrimitive:
1140 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1141 return false;
1142
1143 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001144 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001145 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001146 }
John Kessenich140f3df2015-06-26 16:58:36 -06001147}
1148
1149bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1150{
qining27e04a02016-04-14 16:40:20 -04001151 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1152 if (node->getType().getQualifier().isSpecConstant())
1153 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1154
John Kessenichfc51d282015-08-19 13:34:18 -06001155 spv::Id result = spv::NoResult;
1156
1157 // try texturing
1158 result = createImageTextureFunctionCall(node);
1159 if (result != spv::NoResult) {
1160 builder.clearAccessChain();
1161 builder.setAccessChainRValue(result);
1162
1163 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001164 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001165 // "imageStore" is a special case, which has no result
1166 return false;
1167 }
John Kessenichfc51d282015-08-19 13:34:18 -06001168
John Kessenich140f3df2015-06-26 16:58:36 -06001169 glslang::TOperator binOp = glslang::EOpNull;
1170 bool reduceComparison = true;
1171 bool isMatrix = false;
1172 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001173 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 assert(node->getOp());
1176
1177 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1178
1179 switch (node->getOp()) {
1180 case glslang::EOpSequence:
1181 {
1182 if (preVisit)
1183 ++sequenceDepth;
1184 else
1185 --sequenceDepth;
1186
1187 if (sequenceDepth == 1) {
1188 // If this is the parent node of all the functions, we want to see them
1189 // early, so all call points have actual SPIR-V functions to reference.
1190 // In all cases, still let the traverser visit the children for us.
1191 makeFunctions(node->getAsAggregate()->getSequence());
1192
1193 // Also, we want all globals initializers to go into the entry of main(), before
1194 // anything else gets there, so visit out of order, doing them all now.
1195 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1196
1197 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1198 // so do them manually.
1199 visitFunctions(node->getAsAggregate()->getSequence());
1200
1201 return false;
1202 }
1203
1204 return true;
1205 }
1206 case glslang::EOpLinkerObjects:
1207 {
1208 if (visit == glslang::EvPreVisit)
1209 linkageOnly = true;
1210 else
1211 linkageOnly = false;
1212
1213 return true;
1214 }
1215 case glslang::EOpComma:
1216 {
1217 // processing from left to right naturally leaves the right-most
1218 // lying around in the access chain
1219 glslang::TIntermSequence& glslangOperands = node->getSequence();
1220 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1221 glslangOperands[i]->traverse(this);
1222
1223 return false;
1224 }
1225 case glslang::EOpFunction:
1226 if (visit == glslang::EvPreVisit) {
1227 if (isShaderEntrypoint(node)) {
1228 inMain = true;
1229 builder.setBuildPoint(shaderEntry->getLastBlock());
1230 } else {
1231 handleFunctionEntry(node);
1232 }
1233 } else {
1234 if (inMain)
1235 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001236 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001237 inMain = false;
1238 }
1239
1240 return true;
1241 case glslang::EOpParameters:
1242 // Parameters will have been consumed by EOpFunction processing, but not
1243 // the body, so we still visited the function node's children, making this
1244 // child redundant.
1245 return false;
1246 case glslang::EOpFunctionCall:
1247 {
1248 if (node->isUserDefined())
1249 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001250 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1251 if (result) {
1252 builder.clearAccessChain();
1253 builder.setAccessChainRValue(result);
1254 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001255 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001256
1257 return false;
1258 }
1259 case glslang::EOpConstructMat2x2:
1260 case glslang::EOpConstructMat2x3:
1261 case glslang::EOpConstructMat2x4:
1262 case glslang::EOpConstructMat3x2:
1263 case glslang::EOpConstructMat3x3:
1264 case glslang::EOpConstructMat3x4:
1265 case glslang::EOpConstructMat4x2:
1266 case glslang::EOpConstructMat4x3:
1267 case glslang::EOpConstructMat4x4:
1268 case glslang::EOpConstructDMat2x2:
1269 case glslang::EOpConstructDMat2x3:
1270 case glslang::EOpConstructDMat2x4:
1271 case glslang::EOpConstructDMat3x2:
1272 case glslang::EOpConstructDMat3x3:
1273 case glslang::EOpConstructDMat3x4:
1274 case glslang::EOpConstructDMat4x2:
1275 case glslang::EOpConstructDMat4x3:
1276 case glslang::EOpConstructDMat4x4:
1277 isMatrix = true;
1278 // fall through
1279 case glslang::EOpConstructFloat:
1280 case glslang::EOpConstructVec2:
1281 case glslang::EOpConstructVec3:
1282 case glslang::EOpConstructVec4:
1283 case glslang::EOpConstructDouble:
1284 case glslang::EOpConstructDVec2:
1285 case glslang::EOpConstructDVec3:
1286 case glslang::EOpConstructDVec4:
1287 case glslang::EOpConstructBool:
1288 case glslang::EOpConstructBVec2:
1289 case glslang::EOpConstructBVec3:
1290 case glslang::EOpConstructBVec4:
1291 case glslang::EOpConstructInt:
1292 case glslang::EOpConstructIVec2:
1293 case glslang::EOpConstructIVec3:
1294 case glslang::EOpConstructIVec4:
1295 case glslang::EOpConstructUint:
1296 case glslang::EOpConstructUVec2:
1297 case glslang::EOpConstructUVec3:
1298 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001299 case glslang::EOpConstructInt64:
1300 case glslang::EOpConstructI64Vec2:
1301 case glslang::EOpConstructI64Vec3:
1302 case glslang::EOpConstructI64Vec4:
1303 case glslang::EOpConstructUint64:
1304 case glslang::EOpConstructU64Vec2:
1305 case glslang::EOpConstructU64Vec3:
1306 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001307 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001308 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001309 {
1310 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001311 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001312 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1313 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001314 if (node->getOp() == glslang::EOpConstructTextureSampler)
1315 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1316 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001317 std::vector<spv::Id> constituents;
1318 for (int c = 0; c < (int)arguments.size(); ++c)
1319 constituents.push_back(arguments[c]);
1320 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001321 } else if (isMatrix)
1322 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1323 else
1324 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001325
1326 builder.clearAccessChain();
1327 builder.setAccessChainRValue(constructed);
1328
1329 return false;
1330 }
1331
1332 // These six are component-wise compares with component-wise results.
1333 // Forward on to createBinaryOperation(), requesting a vector result.
1334 case glslang::EOpLessThan:
1335 case glslang::EOpGreaterThan:
1336 case glslang::EOpLessThanEqual:
1337 case glslang::EOpGreaterThanEqual:
1338 case glslang::EOpVectorEqual:
1339 case glslang::EOpVectorNotEqual:
1340 {
1341 // Map the operation to a binary
1342 binOp = node->getOp();
1343 reduceComparison = false;
1344 switch (node->getOp()) {
1345 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1346 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1347 default: binOp = node->getOp(); break;
1348 }
1349
1350 break;
1351 }
1352 case glslang::EOpMul:
1353 // compontent-wise matrix multiply
1354 binOp = glslang::EOpMul;
1355 break;
1356 case glslang::EOpOuterProduct:
1357 // two vectors multiplied to make a matrix
1358 binOp = glslang::EOpOuterProduct;
1359 break;
1360 case glslang::EOpDot:
1361 {
1362 // for scalar dot product, use multiply
1363 glslang::TIntermSequence& glslangOperands = node->getSequence();
1364 if (! glslangOperands[0]->getAsTyped()->isVector())
1365 binOp = glslang::EOpMul;
1366 break;
1367 }
1368 case glslang::EOpMod:
1369 // when an aggregate, this is the floating-point mod built-in function,
1370 // which can be emitted by the one in createBinaryOperation()
1371 binOp = glslang::EOpMod;
1372 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001373 case glslang::EOpEmitVertex:
1374 case glslang::EOpEndPrimitive:
1375 case glslang::EOpBarrier:
1376 case glslang::EOpMemoryBarrier:
1377 case glslang::EOpMemoryBarrierAtomicCounter:
1378 case glslang::EOpMemoryBarrierBuffer:
1379 case glslang::EOpMemoryBarrierImage:
1380 case glslang::EOpMemoryBarrierShared:
1381 case glslang::EOpGroupMemoryBarrier:
1382 noReturnValue = true;
1383 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1384 break;
1385
John Kessenich426394d2015-07-23 10:22:48 -06001386 case glslang::EOpAtomicAdd:
1387 case glslang::EOpAtomicMin:
1388 case glslang::EOpAtomicMax:
1389 case glslang::EOpAtomicAnd:
1390 case glslang::EOpAtomicOr:
1391 case glslang::EOpAtomicXor:
1392 case glslang::EOpAtomicExchange:
1393 case glslang::EOpAtomicCompSwap:
1394 atomic = true;
1395 break;
1396
John Kessenich140f3df2015-06-26 16:58:36 -06001397 default:
1398 break;
1399 }
1400
1401 //
1402 // See if it maps to a regular operation.
1403 //
John Kessenich140f3df2015-06-26 16:58:36 -06001404 if (binOp != glslang::EOpNull) {
1405 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1406 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1407 assert(left && right);
1408
1409 builder.clearAccessChain();
1410 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001411 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001412
1413 builder.clearAccessChain();
1414 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001415 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001416
1417 result = createBinaryOperation(binOp, precision,
1418 convertGlslangToSpvType(node->getType()), leftId, rightId,
1419 left->getType().getBasicType(), reduceComparison);
1420
1421 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001422 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001423 builder.clearAccessChain();
1424 builder.setAccessChainRValue(result);
1425
1426 return false;
1427 }
1428
John Kessenich426394d2015-07-23 10:22:48 -06001429 //
1430 // Create the list of operands.
1431 //
John Kessenich140f3df2015-06-26 16:58:36 -06001432 glslang::TIntermSequence& glslangOperands = node->getSequence();
1433 std::vector<spv::Id> operands;
1434 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1435 builder.clearAccessChain();
1436 glslangOperands[arg]->traverse(this);
1437
1438 // special case l-value operands; there are just a few
1439 bool lvalue = false;
1440 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001441 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001442 case glslang::EOpModf:
1443 if (arg == 1)
1444 lvalue = true;
1445 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001446 case glslang::EOpInterpolateAtSample:
1447 case glslang::EOpInterpolateAtOffset:
1448 if (arg == 0)
1449 lvalue = true;
1450 break;
Rex Xud4782c12015-09-06 16:30:11 +08001451 case glslang::EOpAtomicAdd:
1452 case glslang::EOpAtomicMin:
1453 case glslang::EOpAtomicMax:
1454 case glslang::EOpAtomicAnd:
1455 case glslang::EOpAtomicOr:
1456 case glslang::EOpAtomicXor:
1457 case glslang::EOpAtomicExchange:
1458 case glslang::EOpAtomicCompSwap:
1459 if (arg == 0)
1460 lvalue = true;
1461 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001462 case glslang::EOpAddCarry:
1463 case glslang::EOpSubBorrow:
1464 if (arg == 2)
1465 lvalue = true;
1466 break;
1467 case glslang::EOpUMulExtended:
1468 case glslang::EOpIMulExtended:
1469 if (arg >= 2)
1470 lvalue = true;
1471 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001472 default:
1473 break;
1474 }
1475 if (lvalue)
1476 operands.push_back(builder.accessChainGetLValue());
1477 else
John Kessenich32cfd492016-02-02 12:37:46 -07001478 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001479 }
John Kessenich426394d2015-07-23 10:22:48 -06001480
1481 if (atomic) {
1482 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001483 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001484 } else {
1485 // Pass through to generic operations.
1486 switch (glslangOperands.size()) {
1487 case 0:
1488 result = createNoArgOperation(node->getOp());
1489 break;
1490 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001491 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001492 break;
1493 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001494 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001495 break;
1496 }
John Kessenich140f3df2015-06-26 16:58:36 -06001497 }
1498
1499 if (noReturnValue)
1500 return false;
1501
1502 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001503 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001504 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001505 } else {
1506 builder.clearAccessChain();
1507 builder.setAccessChainRValue(result);
1508 return false;
1509 }
1510}
1511
1512bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1513{
1514 // This path handles both if-then-else and ?:
1515 // The if-then-else has a node type of void, while
1516 // ?: has a non-void node type
1517 spv::Id result = 0;
1518 if (node->getBasicType() != glslang::EbtVoid) {
1519 // don't handle this as just on-the-fly temporaries, because there will be two names
1520 // and better to leave SSA to later passes
1521 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1522 }
1523
1524 // emit the condition before doing anything with selection
1525 node->getCondition()->traverse(this);
1526
1527 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001528 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001529
1530 if (node->getTrueBlock()) {
1531 // emit the "then" statement
1532 node->getTrueBlock()->traverse(this);
1533 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001534 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001535 }
1536
1537 if (node->getFalseBlock()) {
1538 ifBuilder.makeBeginElse();
1539 // emit the "else" statement
1540 node->getFalseBlock()->traverse(this);
1541 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001542 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001543 }
1544
1545 ifBuilder.makeEndIf();
1546
1547 if (result) {
1548 // GLSL only has r-values as the result of a :?, but
1549 // if we have an l-value, that can be more efficient if it will
1550 // become the base of a complex r-value expression, because the
1551 // next layer copies r-values into memory to use the access-chain mechanism
1552 builder.clearAccessChain();
1553 builder.setAccessChainLValue(result);
1554 }
1555
1556 return false;
1557}
1558
1559bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1560{
1561 // emit and get the condition before doing anything with switch
1562 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001563 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001564
1565 // browse the children to sort out code segments
1566 int defaultSegment = -1;
1567 std::vector<TIntermNode*> codeSegments;
1568 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1569 std::vector<int> caseValues;
1570 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1571 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1572 TIntermNode* child = *c;
1573 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001574 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001575 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001576 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001577 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1578 } else
1579 codeSegments.push_back(child);
1580 }
1581
1582 // handle the case where the last code segment is missing, due to no code
1583 // statements between the last case and the end of the switch statement
1584 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1585 (int)codeSegments.size() == defaultSegment)
1586 codeSegments.push_back(nullptr);
1587
1588 // make the switch statement
1589 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001590 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001591
1592 // emit all the code in the segments
1593 breakForLoop.push(false);
1594 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1595 builder.nextSwitchSegment(segmentBlocks, s);
1596 if (codeSegments[s])
1597 codeSegments[s]->traverse(this);
1598 else
1599 builder.addSwitchBreak();
1600 }
1601 breakForLoop.pop();
1602
1603 builder.endSwitch(segmentBlocks);
1604
1605 return false;
1606}
1607
1608void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1609{
1610 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001611 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001612
1613 builder.clearAccessChain();
1614 builder.setAccessChainRValue(constant);
1615}
1616
1617bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1618{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001619 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001620 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001621 // Spec requires back edges to target header blocks, and every header block
1622 // must dominate its merge block. Make a header block first to ensure these
1623 // conditions are met. By definition, it will contain OpLoopMerge, followed
1624 // by a block-ending branch. But we don't want to put any other body/test
1625 // instructions in it, since the body/test may have arbitrary instructions,
1626 // including merges of its own.
1627 builder.setBuildPoint(&blocks.head);
1628 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001629 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001630 spv::Block& test = builder.makeNewBlock();
1631 builder.createBranch(&test);
1632
1633 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001634 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001635 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001636 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001637 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1638
1639 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001640 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001641 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001642 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001643 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001644 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001645
1646 builder.setBuildPoint(&blocks.continue_target);
1647 if (node->getTerminal())
1648 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001649 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001650 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001651 builder.createBranch(&blocks.body);
1652
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001653 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654 builder.setBuildPoint(&blocks.body);
1655 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001656 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001657 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001658 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001659
1660 builder.setBuildPoint(&blocks.continue_target);
1661 if (node->getTerminal())
1662 node->getTerminal()->traverse(this);
1663 if (node->getTest()) {
1664 node->getTest()->traverse(this);
1665 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001666 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001667 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001668 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001669 // TODO: unless there was a break/return/discard instruction
1670 // somewhere in the body, this is an infinite loop, so we should
1671 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001672 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673 }
John Kessenich140f3df2015-06-26 16:58:36 -06001674 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001675 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001676 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001677 return false;
1678}
1679
1680bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1681{
1682 if (node->getExpression())
1683 node->getExpression()->traverse(this);
1684
1685 switch (node->getFlowOp()) {
1686 case glslang::EOpKill:
1687 builder.makeDiscard();
1688 break;
1689 case glslang::EOpBreak:
1690 if (breakForLoop.top())
1691 builder.createLoopExit();
1692 else
1693 builder.addSwitchBreak();
1694 break;
1695 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001696 builder.createLoopContinue();
1697 break;
1698 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001699 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001700 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001701 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001702 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001703
1704 builder.clearAccessChain();
1705 break;
1706
1707 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001708 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001709 break;
1710 }
1711
1712 return false;
1713}
1714
1715spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1716{
1717 // First, steer off constants, which are not SPIR-V variables, but
1718 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001719 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001720 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001721 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001722 }
1723
1724 // Now, handle actual variables
1725 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1726 spv::Id spvType = convertGlslangToSpvType(node->getType());
1727
1728 const char* name = node->getName().c_str();
1729 if (glslang::IsAnonymous(name))
1730 name = "";
1731
1732 return builder.createVariable(storageClass, spvType, name);
1733}
1734
1735// Return type Id of the sampled type.
1736spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1737{
1738 switch (sampler.type) {
1739 case glslang::EbtFloat: return builder.makeFloatType(32);
1740 case glslang::EbtInt: return builder.makeIntType(32);
1741 case glslang::EbtUint: return builder.makeUintType(32);
1742 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001743 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 return builder.makeFloatType(32);
1745 }
1746}
1747
John Kessenich3ac051e2015-12-20 11:29:16 -07001748// Convert from a glslang type to an SPV type, by calling into a
1749// recursive version of this function. This establishes the inherited
1750// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001751spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1752{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001753 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001754}
1755
1756// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001757// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001758spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001759{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001760 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001761
1762 switch (type.getBasicType()) {
1763 case glslang::EbtVoid:
1764 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001765 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001766 break;
1767 case glslang::EbtFloat:
1768 spvType = builder.makeFloatType(32);
1769 break;
1770 case glslang::EbtDouble:
1771 spvType = builder.makeFloatType(64);
1772 break;
1773 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001774 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1775 // a 32-bit int where non-0 means true.
1776 if (explicitLayout != glslang::ElpNone)
1777 spvType = builder.makeUintType(32);
1778 else
1779 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001780 break;
1781 case glslang::EbtInt:
1782 spvType = builder.makeIntType(32);
1783 break;
1784 case glslang::EbtUint:
1785 spvType = builder.makeUintType(32);
1786 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001787 case glslang::EbtInt64:
1788 builder.addCapability(spv::CapabilityInt64);
1789 spvType = builder.makeIntType(64);
1790 break;
1791 case glslang::EbtUint64:
1792 builder.addCapability(spv::CapabilityInt64);
1793 spvType = builder.makeUintType(64);
1794 break;
John Kessenich426394d2015-07-23 10:22:48 -06001795 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001796 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 -06001797 spvType = builder.makeUintType(32);
1798 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001799 case glslang::EbtSampler:
1800 {
1801 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001802 if (sampler.sampler) {
1803 // pure sampler
1804 spvType = builder.makeSamplerType();
1805 } else {
1806 // an image is present, make its type
1807 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1808 sampler.image ? 2 : 1, TranslateImageFormat(type));
1809 if (sampler.combined) {
1810 // already has both image and sampler, make the combined type
1811 spvType = builder.makeSampledImageType(spvType);
1812 }
John Kessenich55e7d112015-11-15 21:33:39 -07001813 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001814 }
John Kessenich140f3df2015-06-26 16:58:36 -06001815 break;
1816 case glslang::EbtStruct:
1817 case glslang::EbtBlock:
1818 {
1819 // If we've seen this struct type, return it
1820 const glslang::TTypeList* glslangStruct = type.getStruct();
1821 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001822
1823 // Try to share structs for different layouts, but not yet for other
1824 // kinds of qualification (primarily not yet including interpolant qualification).
1825 if (! HasNonLayoutQualifiers(qualifier))
1826 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1827 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001828 break;
1829
1830 // else, we haven't seen it...
1831
1832 // Create a vector of struct types for SPIR-V to consume
1833 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1834 if (type.getBasicType() == glslang::EbtBlock)
1835 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001836 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001837 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1838 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1839 if (glslangType.hiddenMember()) {
1840 ++memberDelta;
1841 if (type.getBasicType() == glslang::EbtBlock)
1842 memberRemapper[glslangStruct][i] = -1;
1843 } else {
1844 if (type.getBasicType() == glslang::EbtBlock)
1845 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001846 // modify just this child's view of the qualifier
1847 glslang::TQualifier subQualifier = glslangType.getQualifier();
1848 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001849
1850 // manually inherit location; it's more complex
1851 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1852 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1853 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001854 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001855
1856 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001857 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001858 }
1859 }
1860
1861 // Make the SPIR-V type
1862 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001863 if (! HasNonLayoutQualifiers(qualifier))
1864 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001865
1866 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001867 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001868 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001869 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1870 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1871 int member = i;
1872 if (type.getBasicType() == glslang::EbtBlock)
1873 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001874
John Kesseniche0b6cad2015-12-24 10:30:13 -07001875 // modify just this child's view of the qualifier
1876 glslang::TQualifier subQualifier = glslangType.getQualifier();
1877 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001878
John Kessenich140f3df2015-06-26 16:58:36 -06001879 // using -1 above to indicate a hidden member
1880 if (member >= 0) {
1881 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001882 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001883 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001884 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1885 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001886
Rex Xu1da878f2016-02-21 20:59:01 +08001887 if (qualifier.storage == glslang::EvqBuffer) {
1888 std::vector<spv::Decoration> memory;
1889 TranslateMemoryDecoration(subQualifier, memory);
1890 for (unsigned int i = 0; i < memory.size(); ++i)
1891 addMemberDecoration(spvType, member, memory[i]);
1892 }
1893
John Kessenich09677482016-02-19 12:21:50 -07001894 // compute location decoration; tricky based on whether inheritance is at play
1895 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1896 // probably move to the linker stage of the front end proper, and just have the
1897 // answer sitting already distributed throughout the individual member locations.
1898 int location = -1; // will only decorate if present or inherited
1899 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1900 location = subQualifier.layoutLocation;
1901 else if (qualifier.hasLocation()) // inheritance
1902 location = qualifier.layoutLocation + locationOffset;
1903 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001904 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001905 if (location >= 0)
1906 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1907
1908 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001909 if (glslangType.getQualifier().hasComponent())
1910 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1911 if (glslangType.getQualifier().hasXfbOffset())
1912 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001913 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001914 // figure out what to do with offset, which is accumulating
1915 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001916 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001917 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001918 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001919 offset = nextOffset;
1920 }
John Kessenich140f3df2015-06-26 16:58:36 -06001921
John Kessenichf85e8062015-12-19 13:57:10 -07001922 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001923 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001924
John Kessenich140f3df2015-06-26 16:58:36 -06001925 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001926 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1927 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001928 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001929 }
1930 }
1931
1932 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001933 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001934 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001935 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001936 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001937 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001938 }
John Kessenich140f3df2015-06-26 16:58:36 -06001939 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001940 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001941 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001942 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001943 if (type.getQualifier().hasXfbBuffer())
1944 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1945 }
1946 }
1947 break;
1948 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001949 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 break;
1951 }
1952
1953 if (type.isMatrix())
1954 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1955 else {
1956 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1957 if (type.getVectorSize() > 1)
1958 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1959 }
1960
1961 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001962 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1963
John Kessenichc9a80832015-09-12 12:17:44 -06001964 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001965 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001966 // We need to decorate array strides for types needing explicit layout, except blocks.
1967 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001968 // Use a dummy glslang type for querying internal strides of
1969 // arrays of arrays, but using just a one-dimensional array.
1970 glslang::TType simpleArrayType(type, 0); // deference type of the array
1971 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1972 simpleArrayType.getArraySizes().dereference();
1973
1974 // Will compute the higher-order strides here, rather than making a whole
1975 // pile of types and doing repetitive recursion on their contents.
1976 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1977 }
John Kessenichf8842e52016-01-04 19:22:56 -07001978
1979 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001980 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001981 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001982 if (stride > 0)
1983 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001984 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001985 }
1986 } else {
1987 // single-dimensional array, and don't yet have stride
1988
John Kessenichf8842e52016-01-04 19:22:56 -07001989 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001990 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1991 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001992 }
John Kessenich31ed4832015-09-09 17:51:38 -06001993
John Kessenichc9a80832015-09-12 12:17:44 -06001994 // Do the outer dimension, which might not be known for a runtime-sized array
1995 if (type.isRuntimeSizedArray()) {
1996 spvType = builder.makeRuntimeArray(spvType);
1997 } else {
1998 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001999 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002000 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002001 if (stride > 0)
2002 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002003 }
2004
2005 return spvType;
2006}
2007
John Kessenich6c292d32016-02-15 20:58:50 -07002008// Turn the expression forming the array size into an id.
2009// This is not quite trivial, because of specialization constants.
2010// Sometimes, a raw constant is turned into an Id, and sometimes
2011// a specialization constant expression is.
2012spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2013{
2014 // First, see if this is sized with a node, meaning a specialization constant:
2015 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2016 if (specNode != nullptr) {
2017 builder.clearAccessChain();
2018 specNode->traverse(this);
2019 return accessChainLoad(specNode->getAsTyped()->getType());
2020 }
2021
2022 // Otherwise, need a compile-time (front end) size, get it:
2023 int size = arraySizes.getDimSize(dim);
2024 assert(size > 0);
2025 return builder.makeUintConstant(size);
2026}
2027
John Kessenich103bef92016-02-08 21:38:15 -07002028// Wrap the builder's accessChainLoad to:
2029// - localize handling of RelaxedPrecision
2030// - use the SPIR-V inferred type instead of another conversion of the glslang type
2031// (avoids unnecessary work and possible type punning for structures)
2032// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002033spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2034{
John Kessenich103bef92016-02-08 21:38:15 -07002035 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2036 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2037
2038 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002039 if (type.getBasicType() == glslang::EbtBool) {
2040 if (builder.isScalarType(nominalTypeId)) {
2041 // Conversion for bool
2042 spv::Id boolType = builder.makeBoolType();
2043 if (nominalTypeId != boolType)
2044 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2045 } else if (builder.isVectorType(nominalTypeId)) {
2046 // Conversion for bvec
2047 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2048 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2049 if (nominalTypeId != bvecType)
2050 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2051 }
2052 }
John Kessenich103bef92016-02-08 21:38:15 -07002053
2054 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002055}
2056
Rex Xu27253232016-02-23 17:51:09 +08002057// Wrap the builder's accessChainStore to:
2058// - do conversion of concrete to abstract type
2059void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2060{
2061 // Need to convert to abstract types when necessary
2062 if (type.getBasicType() == glslang::EbtBool) {
2063 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2064
2065 if (builder.isScalarType(nominalTypeId)) {
2066 // Conversion for bool
2067 spv::Id boolType = builder.makeBoolType();
2068 if (nominalTypeId != boolType) {
2069 spv::Id zero = builder.makeUintConstant(0);
2070 spv::Id one = builder.makeUintConstant(1);
2071 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2072 }
2073 } else if (builder.isVectorType(nominalTypeId)) {
2074 // Conversion for bvec
2075 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2076 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2077 if (nominalTypeId != bvecType) {
2078 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2079 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2080 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2081 }
2082 }
2083 }
2084
2085 builder.accessChainStore(rvalue);
2086}
2087
John Kessenichf85e8062015-12-19 13:57:10 -07002088// Decide whether or not this type should be
2089// decorated with offsets and strides, and if so
2090// whether std140 or std430 rules should be applied.
2091glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002092{
John Kessenichf85e8062015-12-19 13:57:10 -07002093 // has to be a block
2094 if (type.getBasicType() != glslang::EbtBlock)
2095 return glslang::ElpNone;
2096
2097 // has to be a uniform or buffer block
2098 if (type.getQualifier().storage != glslang::EvqUniform &&
2099 type.getQualifier().storage != glslang::EvqBuffer)
2100 return glslang::ElpNone;
2101
2102 // return the layout to use
2103 switch (type.getQualifier().layoutPacking) {
2104 case glslang::ElpStd140:
2105 case glslang::ElpStd430:
2106 return type.getQualifier().layoutPacking;
2107 default:
2108 return glslang::ElpNone;
2109 }
John Kessenich31ed4832015-09-09 17:51:38 -06002110}
2111
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002112// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002113int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002114{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002115 int size;
John Kessenich49987892015-12-29 17:11:44 -07002116 int stride;
2117 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002118
2119 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002120}
2121
John Kessenich49987892015-12-29 17:11:44 -07002122// 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 -07002123// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002124int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002125{
John Kessenich49987892015-12-29 17:11:44 -07002126 glslang::TType elementType;
2127 elementType.shallowCopy(matrixType);
2128 elementType.clearArraySizes();
2129
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002130 int size;
John Kessenich49987892015-12-29 17:11:44 -07002131 int stride;
2132 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2133
2134 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002135}
2136
John Kessenich5e4b1242015-08-06 22:53:06 -06002137// Given a member type of a struct, realign the current offset for it, and compute
2138// the next (not yet aligned) offset for the next member, which will get aligned
2139// on the next call.
2140// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2141// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2142// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002143void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002144 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002145{
2146 // this will get a positive value when deemed necessary
2147 nextOffset = -1;
2148
John Kessenich5e4b1242015-08-06 22:53:06 -06002149 // override anything in currentOffset with user-set offset
2150 if (memberType.getQualifier().hasOffset())
2151 currentOffset = memberType.getQualifier().layoutOffset;
2152
2153 // It could be that current linker usage in glslang updated all the layoutOffset,
2154 // in which case the following code does not matter. But, that's not quite right
2155 // once cross-compilation unit GLSL validation is done, as the original user
2156 // settings are needed in layoutOffset, and then the following will come into play.
2157
John Kessenichf85e8062015-12-19 13:57:10 -07002158 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002159 if (! memberType.getQualifier().hasOffset())
2160 currentOffset = -1;
2161
2162 return;
2163 }
2164
John Kessenichf85e8062015-12-19 13:57:10 -07002165 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002166 if (currentOffset < 0)
2167 currentOffset = 0;
2168
2169 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2170 // but possibly not yet correctly aligned.
2171
2172 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002173 int dummyStride;
2174 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002175 glslang::RoundToPow2(currentOffset, memberAlignment);
2176 nextOffset = currentOffset + memberSize;
2177}
2178
John Kessenich140f3df2015-06-26 16:58:36 -06002179bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2180{
John Kessenich4d65ee32016-03-12 18:17:47 -07002181 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002182 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002183 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002184}
2185
2186// Make all the functions, skeletally, without actually visiting their bodies.
2187void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2188{
2189 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2190 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2191 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2192 continue;
2193
2194 // We're on a user function. Set up the basic interface for the function now,
2195 // so that it's available to call.
2196 // Translating the body will happen later.
2197 //
2198 // Typically (except for a "const in" parameter), an address will be passed to the
2199 // function. What it is an address of varies:
2200 //
2201 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2202 // so that write needs to be to a copy, hence the address of a copy works.
2203 //
2204 // - "const in" parameters can just be the r-value, as no writes need occur.
2205 //
2206 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2207 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2208
2209 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002210 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002211 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2212
2213 for (int p = 0; p < (int)parameters.size(); ++p) {
2214 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2215 spv::Id typeId = convertGlslangToSpvType(paramType);
2216 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2217 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2218 else
2219 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002220 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002221 paramTypes.push_back(typeId);
2222 }
2223
2224 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002225 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2226 convertGlslangToSpvType(glslFunction->getType()),
2227 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002228
2229 // Track function to emit/call later
2230 functionMap[glslFunction->getName().c_str()] = function;
2231
2232 // Set the parameter id's
2233 for (int p = 0; p < (int)parameters.size(); ++p) {
2234 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2235 // give a name too
2236 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2237 }
2238 }
2239}
2240
2241// Process all the initializers, while skipping the functions and link objects
2242void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2243{
2244 builder.setBuildPoint(shaderEntry->getLastBlock());
2245 for (int i = 0; i < (int)initializers.size(); ++i) {
2246 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2247 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2248
2249 // We're on a top-level node that's not a function. Treat as an initializer, whose
2250 // code goes into the beginning of main.
2251 initializer->traverse(this);
2252 }
2253 }
2254}
2255
2256// Process all the functions, while skipping initializers.
2257void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2258{
2259 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2260 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2261 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2262 node->traverse(this);
2263 }
2264}
2265
2266void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2267{
2268 // SPIR-V functions should already be in the functionMap from the prepass
2269 // that called makeFunctions().
2270 spv::Function* function = functionMap[node->getName().c_str()];
2271 spv::Block* functionBlock = function->getEntryBlock();
2272 builder.setBuildPoint(functionBlock);
2273}
2274
Rex Xu04db3f52015-09-16 11:44:02 +08002275void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002276{
Rex Xufc618912015-09-09 16:42:49 +08002277 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002278
2279 glslang::TSampler sampler = {};
2280 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002281 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002282 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2283 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2284 }
2285
John Kessenich140f3df2015-06-26 16:58:36 -06002286 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2287 builder.clearAccessChain();
2288 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002289
2290 // Special case l-value operands
2291 bool lvalue = false;
2292 switch (node.getOp()) {
2293 case glslang::EOpImageAtomicAdd:
2294 case glslang::EOpImageAtomicMin:
2295 case glslang::EOpImageAtomicMax:
2296 case glslang::EOpImageAtomicAnd:
2297 case glslang::EOpImageAtomicOr:
2298 case glslang::EOpImageAtomicXor:
2299 case glslang::EOpImageAtomicExchange:
2300 case glslang::EOpImageAtomicCompSwap:
2301 if (i == 0)
2302 lvalue = true;
2303 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002304 case glslang::EOpSparseImageLoad:
2305 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2306 lvalue = true;
2307 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002308 case glslang::EOpSparseTexture:
2309 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2310 lvalue = true;
2311 break;
2312 case glslang::EOpSparseTextureClamp:
2313 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2314 lvalue = true;
2315 break;
2316 case glslang::EOpSparseTextureLod:
2317 case glslang::EOpSparseTextureOffset:
2318 if (i == 3)
2319 lvalue = true;
2320 break;
2321 case glslang::EOpSparseTextureFetch:
2322 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2323 lvalue = true;
2324 break;
2325 case glslang::EOpSparseTextureFetchOffset:
2326 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2327 lvalue = true;
2328 break;
2329 case glslang::EOpSparseTextureLodOffset:
2330 case glslang::EOpSparseTextureGrad:
2331 case glslang::EOpSparseTextureOffsetClamp:
2332 if (i == 4)
2333 lvalue = true;
2334 break;
2335 case glslang::EOpSparseTextureGradOffset:
2336 case glslang::EOpSparseTextureGradClamp:
2337 if (i == 5)
2338 lvalue = true;
2339 break;
2340 case glslang::EOpSparseTextureGradOffsetClamp:
2341 if (i == 6)
2342 lvalue = true;
2343 break;
2344 case glslang::EOpSparseTextureGather:
2345 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2346 lvalue = true;
2347 break;
2348 case glslang::EOpSparseTextureGatherOffset:
2349 case glslang::EOpSparseTextureGatherOffsets:
2350 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2351 lvalue = true;
2352 break;
Rex Xufc618912015-09-09 16:42:49 +08002353 default:
2354 break;
2355 }
2356
Rex Xu6b86d492015-09-16 17:48:22 +08002357 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002358 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002359 else
John Kessenich32cfd492016-02-02 12:37:46 -07002360 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002361 }
2362}
2363
John Kessenichfc51d282015-08-19 13:34:18 -06002364void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002365{
John Kessenichfc51d282015-08-19 13:34:18 -06002366 builder.clearAccessChain();
2367 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002368 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002369}
John Kessenich140f3df2015-06-26 16:58:36 -06002370
John Kessenichfc51d282015-08-19 13:34:18 -06002371spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2372{
Rex Xufc618912015-09-09 16:42:49 +08002373 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002374 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002375 }
2376
John Kessenichfc51d282015-08-19 13:34:18 -06002377 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002378 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2379 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2380 std::vector<spv::Id> arguments;
2381 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002382 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002383 else
2384 translateArguments(*node->getAsUnaryNode(), arguments);
2385 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2386
2387 spv::Builder::TextureParameters params = { };
2388 params.sampler = arguments[0];
2389
Rex Xu04db3f52015-09-16 11:44:02 +08002390 glslang::TCrackedTextureOp cracked;
2391 node->crackTexture(sampler, cracked);
2392
John Kessenichfc51d282015-08-19 13:34:18 -06002393 // Check for queries
2394 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002395 // a sampled image needs to have the image extracted first
2396 if (builder.isSampledImage(params.sampler))
2397 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002398 switch (node->getOp()) {
2399 case glslang::EOpImageQuerySize:
2400 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002401 if (arguments.size() > 1) {
2402 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002403 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002404 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002405 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002406 case glslang::EOpImageQuerySamples:
2407 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002408 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002409 case glslang::EOpTextureQueryLod:
2410 params.coords = arguments[1];
2411 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2412 case glslang::EOpTextureQueryLevels:
2413 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002414 case glslang::EOpSparseTexelsResident:
2415 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002416 default:
2417 assert(0);
2418 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002419 }
John Kessenich140f3df2015-06-26 16:58:36 -06002420 }
2421
Rex Xufc618912015-09-09 16:42:49 +08002422 // Check for image functions other than queries
2423 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002424 std::vector<spv::Id> operands;
2425 auto opIt = arguments.begin();
2426 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002427
2428 // Handle subpass operations
2429 // TODO: GLSL should change to have the "MS" only on the type rather than the
2430 // built-in function.
2431 if (cracked.subpass) {
2432 // add on the (0,0) coordinate
2433 spv::Id zero = builder.makeIntConstant(0);
2434 std::vector<spv::Id> comps;
2435 comps.push_back(zero);
2436 comps.push_back(zero);
2437 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2438 if (sampler.ms) {
2439 operands.push_back(spv::ImageOperandsSampleMask);
2440 operands.push_back(*(opIt++));
2441 }
2442 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2443 }
2444
John Kessenich56bab042015-09-16 10:54:31 -06002445 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002446 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002447 if (sampler.ms) {
2448 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002449 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002450 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002451 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2452 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002453 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002454 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002455 if (sampler.ms) {
2456 operands.push_back(*(opIt + 1));
2457 operands.push_back(spv::ImageOperandsSampleMask);
2458 operands.push_back(*opIt);
2459 } else
2460 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002461 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002462 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2463 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002464 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002465 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2466 builder.addCapability(spv::CapabilitySparseResidency);
2467 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2468 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2469
2470 if (sampler.ms) {
2471 operands.push_back(spv::ImageOperandsSampleMask);
2472 operands.push_back(*opIt++);
2473 }
2474
2475 // Create the return type that was a special structure
2476 spv::Id texelOut = *opIt;
2477 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2478 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2479 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2480
2481 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2482
2483 // Decode the return type
2484 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2485 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002486 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002487 // Process image atomic operations
2488
2489 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2490 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002491 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002492
Rex Xufc618912015-09-09 16:42:49 +08002493 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002494 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002495
2496 std::vector<spv::Id> operands;
2497 operands.push_back(pointer);
2498 for (; opIt != arguments.end(); ++opIt)
2499 operands.push_back(*opIt);
2500
Rex Xu04db3f52015-09-16 11:44:02 +08002501 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002502 }
2503 }
2504
2505 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002506 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002507 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2508
John Kessenichfc51d282015-08-19 13:34:18 -06002509 // check for bias argument
2510 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002511 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002512 int nonBiasArgCount = 2;
2513 if (cracked.offset)
2514 ++nonBiasArgCount;
2515 if (cracked.grad)
2516 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002517 if (cracked.lodClamp)
2518 ++nonBiasArgCount;
2519 if (sparse)
2520 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002521
2522 if ((int)arguments.size() > nonBiasArgCount)
2523 bias = true;
2524 }
2525
John Kessenichfc51d282015-08-19 13:34:18 -06002526 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002527
John Kessenichfc51d282015-08-19 13:34:18 -06002528 params.coords = arguments[1];
2529 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002530 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002531
2532 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002533 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002534 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002535 ++extraArgs;
2536 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002537 params.Dref = arguments[2];
2538 ++extraArgs;
2539 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002540 std::vector<spv::Id> indexes;
2541 int comp;
2542 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002543 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002544 else
2545 comp = builder.getNumComponents(params.coords) - 1;
2546 indexes.push_back(comp);
2547 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2548 }
2549 if (cracked.lod) {
2550 params.lod = arguments[2];
2551 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002552 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2553 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2554 noImplicitLod = true;
2555 }
2556 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002557 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002558 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002559 }
2560 if (cracked.grad) {
2561 params.gradX = arguments[2 + extraArgs];
2562 params.gradY = arguments[3 + extraArgs];
2563 extraArgs += 2;
2564 }
John Kessenich55e7d112015-11-15 21:33:39 -07002565 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002566 params.offset = arguments[2 + extraArgs];
2567 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002568 } else if (cracked.offsets) {
2569 params.offsets = arguments[2 + extraArgs];
2570 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002571 }
Rex Xu48edadf2015-12-31 16:11:41 +08002572 if (cracked.lodClamp) {
2573 params.lodClamp = arguments[2 + extraArgs];
2574 ++extraArgs;
2575 }
2576 if (sparse) {
2577 params.texelOut = arguments[2 + extraArgs];
2578 ++extraArgs;
2579 }
John Kessenichfc51d282015-08-19 13:34:18 -06002580 if (bias) {
2581 params.bias = arguments[2 + extraArgs];
2582 ++extraArgs;
2583 }
John Kessenich55e7d112015-11-15 21:33:39 -07002584 if (cracked.gather && ! sampler.shadow) {
2585 // default component is 0, if missing, otherwise an argument
2586 if (2 + extraArgs < (int)arguments.size()) {
2587 params.comp = arguments[2 + extraArgs];
2588 ++extraArgs;
2589 } else {
2590 params.comp = builder.makeIntConstant(0);
2591 }
2592 }
John Kessenichfc51d282015-08-19 13:34:18 -06002593
John Kessenich019f08f2016-02-15 15:40:42 -07002594 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002595}
2596
2597spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2598{
2599 // Grab the function's pointer from the previously created function
2600 spv::Function* function = functionMap[node->getName().c_str()];
2601 if (! function)
2602 return 0;
2603
2604 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2605 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2606
2607 // See comments in makeFunctions() for details about the semantics for parameter passing.
2608 //
2609 // These imply we need a four step process:
2610 // 1. Evaluate the arguments
2611 // 2. Allocate and make copies of in, out, and inout arguments
2612 // 3. Make the call
2613 // 4. Copy back the results
2614
2615 // 1. Evaluate the arguments
2616 std::vector<spv::Builder::AccessChain> lValues;
2617 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002618 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002619 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2620 // build l-value
2621 builder.clearAccessChain();
2622 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002623 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002624 // keep outputs as l-values, evaluate input-only as r-values
2625 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2626 // save l-value
2627 lValues.push_back(builder.getAccessChain());
2628 } else {
2629 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002630 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002631 }
2632 }
2633
2634 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2635 // copy the original into that space.
2636 //
2637 // Also, build up the list of actual arguments to pass in for the call
2638 int lValueCount = 0;
2639 int rValueCount = 0;
2640 std::vector<spv::Id> spvArgs;
2641 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2642 spv::Id arg;
2643 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2644 // need space to hold the copy
2645 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2646 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2647 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2648 // need to copy the input into output space
2649 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002650 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002651 builder.createStore(copy, arg);
2652 }
2653 ++lValueCount;
2654 } else {
2655 arg = rValues[rValueCount];
2656 ++rValueCount;
2657 }
2658 spvArgs.push_back(arg);
2659 }
2660
2661 // 3. Make the call.
2662 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002663 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002664
2665 // 4. Copy back out an "out" arguments.
2666 lValueCount = 0;
2667 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2668 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2669 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2670 spv::Id copy = builder.createLoad(spvArgs[a]);
2671 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002672 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002673 }
2674 ++lValueCount;
2675 }
2676 }
2677
2678 return result;
2679}
2680
2681// Translate AST operation to SPV operation, already having SPV-based operands/types.
2682spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2683 spv::Id typeId, spv::Id left, spv::Id right,
2684 glslang::TBasicType typeProxy, bool reduceComparison)
2685{
Rex Xu8ff43de2016-04-22 16:51:45 +08002686 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002688 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002689
2690 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002691 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002692 bool comparison = false;
2693
2694 switch (op) {
2695 case glslang::EOpAdd:
2696 case glslang::EOpAddAssign:
2697 if (isFloat)
2698 binOp = spv::OpFAdd;
2699 else
2700 binOp = spv::OpIAdd;
2701 break;
2702 case glslang::EOpSub:
2703 case glslang::EOpSubAssign:
2704 if (isFloat)
2705 binOp = spv::OpFSub;
2706 else
2707 binOp = spv::OpISub;
2708 break;
2709 case glslang::EOpMul:
2710 case glslang::EOpMulAssign:
2711 if (isFloat)
2712 binOp = spv::OpFMul;
2713 else
2714 binOp = spv::OpIMul;
2715 break;
2716 case glslang::EOpVectorTimesScalar:
2717 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002718 if (isFloat) {
2719 if (builder.isVector(right))
2720 std::swap(left, right);
2721 assert(builder.isScalar(right));
2722 needMatchingVectors = false;
2723 binOp = spv::OpVectorTimesScalar;
2724 } else
2725 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002726 break;
2727 case glslang::EOpVectorTimesMatrix:
2728 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002729 binOp = spv::OpVectorTimesMatrix;
2730 break;
2731 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002732 binOp = spv::OpMatrixTimesVector;
2733 break;
2734 case glslang::EOpMatrixTimesScalar:
2735 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002736 binOp = spv::OpMatrixTimesScalar;
2737 break;
2738 case glslang::EOpMatrixTimesMatrix:
2739 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002740 binOp = spv::OpMatrixTimesMatrix;
2741 break;
2742 case glslang::EOpOuterProduct:
2743 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002744 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
2746
2747 case glslang::EOpDiv:
2748 case glslang::EOpDivAssign:
2749 if (isFloat)
2750 binOp = spv::OpFDiv;
2751 else if (isUnsigned)
2752 binOp = spv::OpUDiv;
2753 else
2754 binOp = spv::OpSDiv;
2755 break;
2756 case glslang::EOpMod:
2757 case glslang::EOpModAssign:
2758 if (isFloat)
2759 binOp = spv::OpFMod;
2760 else if (isUnsigned)
2761 binOp = spv::OpUMod;
2762 else
2763 binOp = spv::OpSMod;
2764 break;
2765 case glslang::EOpRightShift:
2766 case glslang::EOpRightShiftAssign:
2767 if (isUnsigned)
2768 binOp = spv::OpShiftRightLogical;
2769 else
2770 binOp = spv::OpShiftRightArithmetic;
2771 break;
2772 case glslang::EOpLeftShift:
2773 case glslang::EOpLeftShiftAssign:
2774 binOp = spv::OpShiftLeftLogical;
2775 break;
2776 case glslang::EOpAnd:
2777 case glslang::EOpAndAssign:
2778 binOp = spv::OpBitwiseAnd;
2779 break;
2780 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002781 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002782 binOp = spv::OpLogicalAnd;
2783 break;
2784 case glslang::EOpInclusiveOr:
2785 case glslang::EOpInclusiveOrAssign:
2786 binOp = spv::OpBitwiseOr;
2787 break;
2788 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002789 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002790 binOp = spv::OpLogicalOr;
2791 break;
2792 case glslang::EOpExclusiveOr:
2793 case glslang::EOpExclusiveOrAssign:
2794 binOp = spv::OpBitwiseXor;
2795 break;
2796 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002797 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002798 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002799 break;
2800
2801 case glslang::EOpLessThan:
2802 case glslang::EOpGreaterThan:
2803 case glslang::EOpLessThanEqual:
2804 case glslang::EOpGreaterThanEqual:
2805 case glslang::EOpEqual:
2806 case glslang::EOpNotEqual:
2807 case glslang::EOpVectorEqual:
2808 case glslang::EOpVectorNotEqual:
2809 comparison = true;
2810 break;
2811 default:
2812 break;
2813 }
2814
John Kessenich7c1aa102015-10-15 13:29:11 -06002815 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002816 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002817 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002818 if (builder.isMatrix(left) || builder.isMatrix(right))
2819 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002820
2821 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002822 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002823 builder.promoteScalar(precision, left, right);
2824
John Kessenich32cfd492016-02-02 12:37:46 -07002825 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002826 }
2827
2828 if (! comparison)
2829 return 0;
2830
John Kessenich7c1aa102015-10-15 13:29:11 -06002831 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002832
2833 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2834 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2835
John Kessenich22118352015-12-21 20:54:09 -07002836 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002837 }
2838
2839 switch (op) {
2840 case glslang::EOpLessThan:
2841 if (isFloat)
2842 binOp = spv::OpFOrdLessThan;
2843 else if (isUnsigned)
2844 binOp = spv::OpULessThan;
2845 else
2846 binOp = spv::OpSLessThan;
2847 break;
2848 case glslang::EOpGreaterThan:
2849 if (isFloat)
2850 binOp = spv::OpFOrdGreaterThan;
2851 else if (isUnsigned)
2852 binOp = spv::OpUGreaterThan;
2853 else
2854 binOp = spv::OpSGreaterThan;
2855 break;
2856 case glslang::EOpLessThanEqual:
2857 if (isFloat)
2858 binOp = spv::OpFOrdLessThanEqual;
2859 else if (isUnsigned)
2860 binOp = spv::OpULessThanEqual;
2861 else
2862 binOp = spv::OpSLessThanEqual;
2863 break;
2864 case glslang::EOpGreaterThanEqual:
2865 if (isFloat)
2866 binOp = spv::OpFOrdGreaterThanEqual;
2867 else if (isUnsigned)
2868 binOp = spv::OpUGreaterThanEqual;
2869 else
2870 binOp = spv::OpSGreaterThanEqual;
2871 break;
2872 case glslang::EOpEqual:
2873 case glslang::EOpVectorEqual:
2874 if (isFloat)
2875 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002876 else if (isBool)
2877 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002878 else
2879 binOp = spv::OpIEqual;
2880 break;
2881 case glslang::EOpNotEqual:
2882 case glslang::EOpVectorNotEqual:
2883 if (isFloat)
2884 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002885 else if (isBool)
2886 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002887 else
2888 binOp = spv::OpINotEqual;
2889 break;
2890 default:
2891 break;
2892 }
2893
John Kessenich32cfd492016-02-02 12:37:46 -07002894 if (binOp != spv::OpNop)
2895 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002896
2897 return 0;
2898}
2899
John Kessenich04bb8a02015-12-12 12:28:14 -07002900//
2901// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2902// These can be any of:
2903//
2904// matrix * scalar
2905// scalar * matrix
2906// matrix * matrix linear algebraic
2907// matrix * vector
2908// vector * matrix
2909// matrix * matrix componentwise
2910// matrix op matrix op in {+, -, /}
2911// matrix op scalar op in {+, -, /}
2912// scalar op matrix op in {+, -, /}
2913//
2914spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2915{
2916 bool firstClass = true;
2917
2918 // First, handle first-class matrix operations (* and matrix/scalar)
2919 switch (op) {
2920 case spv::OpFDiv:
2921 if (builder.isMatrix(left) && builder.isScalar(right)) {
2922 // turn matrix / scalar into a multiply...
2923 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2924 op = spv::OpMatrixTimesScalar;
2925 } else
2926 firstClass = false;
2927 break;
2928 case spv::OpMatrixTimesScalar:
2929 if (builder.isMatrix(right))
2930 std::swap(left, right);
2931 assert(builder.isScalar(right));
2932 break;
2933 case spv::OpVectorTimesMatrix:
2934 assert(builder.isVector(left));
2935 assert(builder.isMatrix(right));
2936 break;
2937 case spv::OpMatrixTimesVector:
2938 assert(builder.isMatrix(left));
2939 assert(builder.isVector(right));
2940 break;
2941 case spv::OpMatrixTimesMatrix:
2942 assert(builder.isMatrix(left));
2943 assert(builder.isMatrix(right));
2944 break;
2945 default:
2946 firstClass = false;
2947 break;
2948 }
2949
John Kessenich32cfd492016-02-02 12:37:46 -07002950 if (firstClass)
2951 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002952
2953 // Handle component-wise +, -, *, and / for all combinations of type.
2954 // The result type of all of them is the same type as the (a) matrix operand.
2955 // The algorithm is to:
2956 // - break the matrix(es) into vectors
2957 // - smear any scalar to a vector
2958 // - do vector operations
2959 // - make a matrix out the vector results
2960 switch (op) {
2961 case spv::OpFAdd:
2962 case spv::OpFSub:
2963 case spv::OpFDiv:
2964 case spv::OpFMul:
2965 {
2966 // one time set up...
2967 bool leftMat = builder.isMatrix(left);
2968 bool rightMat = builder.isMatrix(right);
2969 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2970 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2971 spv::Id scalarType = builder.getScalarTypeId(typeId);
2972 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2973 std::vector<spv::Id> results;
2974 spv::Id smearVec = spv::NoResult;
2975 if (builder.isScalar(left))
2976 smearVec = builder.smearScalar(precision, left, vecType);
2977 else if (builder.isScalar(right))
2978 smearVec = builder.smearScalar(precision, right, vecType);
2979
2980 // do each vector op
2981 for (unsigned int c = 0; c < numCols; ++c) {
2982 std::vector<unsigned int> indexes;
2983 indexes.push_back(c);
2984 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2985 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2986 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2987 builder.setPrecision(results.back(), precision);
2988 }
2989
2990 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002991 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002992 }
2993 default:
2994 assert(0);
2995 return spv::NoResult;
2996 }
2997}
2998
Rex Xu04db3f52015-09-16 11:44:02 +08002999spv::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 -06003000{
3001 spv::Op unaryOp = spv::OpNop;
3002 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003003 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003004 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003005
3006 switch (op) {
3007 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003008 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003009 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003010 if (builder.isMatrixType(typeId))
3011 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
3012 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003013 unaryOp = spv::OpSNegate;
3014 break;
3015
3016 case glslang::EOpLogicalNot:
3017 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003018 unaryOp = spv::OpLogicalNot;
3019 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 case glslang::EOpBitwiseNot:
3021 unaryOp = spv::OpNot;
3022 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003023
John Kessenich140f3df2015-06-26 16:58:36 -06003024 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030 case glslang::EOpTranspose:
3031 unaryOp = spv::OpTranspose;
3032 break;
3033
3034 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003053 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003054 break;
3055 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058
3059 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003060 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003061 break;
3062 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003063 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003064 break;
3065 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003066 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003067 break;
3068 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003069 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003070 break;
3071 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003072 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003073 break;
3074 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003076 break;
3077
3078 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003079 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003080 break;
3081 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003082 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003083 break;
3084
3085 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003089 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 break;
3100 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003101 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003102 break;
3103
3104 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003105 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003106 break;
3107 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003108 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003109 break;
3110 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003114 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003115 break;
3116 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122
3123 case glslang::EOpIsNan:
3124 unaryOp = spv::OpIsNan;
3125 break;
3126 case glslang::EOpIsInf:
3127 unaryOp = spv::OpIsInf;
3128 break;
3129
Rex Xucbc426e2015-12-15 16:03:10 +08003130 case glslang::EOpFloatBitsToInt:
3131 case glslang::EOpFloatBitsToUint:
3132 case glslang::EOpIntBitsToFloat:
3133 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003134 case glslang::EOpDoubleBitsToInt64:
3135 case glslang::EOpDoubleBitsToUint64:
3136 case glslang::EOpInt64BitsToDouble:
3137 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003138 unaryOp = spv::OpBitcast;
3139 break;
3140
John Kessenich140f3df2015-06-26 16:58:36 -06003141 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003142 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003143 break;
3144 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003145 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003146 break;
3147 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003148 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003149 break;
3150 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003151 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003152 break;
3153 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003154 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003155 break;
3156 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003157 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003158 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003159 case glslang::EOpPackSnorm4x8:
3160 libCall = spv::GLSLstd450PackSnorm4x8;
3161 break;
3162 case glslang::EOpUnpackSnorm4x8:
3163 libCall = spv::GLSLstd450UnpackSnorm4x8;
3164 break;
3165 case glslang::EOpPackUnorm4x8:
3166 libCall = spv::GLSLstd450PackUnorm4x8;
3167 break;
3168 case glslang::EOpUnpackUnorm4x8:
3169 libCall = spv::GLSLstd450UnpackUnorm4x8;
3170 break;
3171 case glslang::EOpPackDouble2x32:
3172 libCall = spv::GLSLstd450PackDouble2x32;
3173 break;
3174 case glslang::EOpUnpackDouble2x32:
3175 libCall = spv::GLSLstd450UnpackDouble2x32;
3176 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003177
Rex Xu8ff43de2016-04-22 16:51:45 +08003178 case glslang::EOpPackInt2x32:
3179 case glslang::EOpUnpackInt2x32:
3180 case glslang::EOpPackUint2x32:
3181 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003182 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003183 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3184 break;
3185
John Kessenich140f3df2015-06-26 16:58:36 -06003186 case glslang::EOpDPdx:
3187 unaryOp = spv::OpDPdx;
3188 break;
3189 case glslang::EOpDPdy:
3190 unaryOp = spv::OpDPdy;
3191 break;
3192 case glslang::EOpFwidth:
3193 unaryOp = spv::OpFwidth;
3194 break;
3195 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003196 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003197 unaryOp = spv::OpDPdxFine;
3198 break;
3199 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003200 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003201 unaryOp = spv::OpDPdyFine;
3202 break;
3203 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003204 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003205 unaryOp = spv::OpFwidthFine;
3206 break;
3207 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003208 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003209 unaryOp = spv::OpDPdxCoarse;
3210 break;
3211 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003212 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003213 unaryOp = spv::OpDPdyCoarse;
3214 break;
3215 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003216 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003217 unaryOp = spv::OpFwidthCoarse;
3218 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003219 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003220 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003221 libCall = spv::GLSLstd450InterpolateAtCentroid;
3222 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003223 case glslang::EOpAny:
3224 unaryOp = spv::OpAny;
3225 break;
3226 case glslang::EOpAll:
3227 unaryOp = spv::OpAll;
3228 break;
3229
3230 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 if (isFloat)
3232 libCall = spv::GLSLstd450FAbs;
3233 else
3234 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003235 break;
3236 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 if (isFloat)
3238 libCall = spv::GLSLstd450FSign;
3239 else
3240 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242
John Kessenichfc51d282015-08-19 13:34:18 -06003243 case glslang::EOpAtomicCounterIncrement:
3244 case glslang::EOpAtomicCounterDecrement:
3245 case glslang::EOpAtomicCounter:
3246 {
3247 // Handle all of the atomics in one place, in createAtomicOperation()
3248 std::vector<spv::Id> operands;
3249 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003250 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003251 }
3252
John Kessenichfc51d282015-08-19 13:34:18 -06003253 case glslang::EOpBitFieldReverse:
3254 unaryOp = spv::OpBitReverse;
3255 break;
3256 case glslang::EOpBitCount:
3257 unaryOp = spv::OpBitCount;
3258 break;
3259 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003260 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003261 break;
3262 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003263 if (isUnsigned)
3264 libCall = spv::GLSLstd450FindUMsb;
3265 else
3266 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003267 break;
3268
Rex Xu574ab042016-04-14 16:53:07 +08003269 case glslang::EOpBallot:
3270 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003271 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003272 libCall = spv::GLSLstd450Bad;
3273 break;
3274
Rex Xu338b1852016-05-05 20:38:33 +08003275 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003276 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003277 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003278 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003279
John Kessenich140f3df2015-06-26 16:58:36 -06003280 default:
3281 return 0;
3282 }
3283
3284 spv::Id id;
3285 if (libCall >= 0) {
3286 std::vector<spv::Id> args;
3287 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003288 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003289 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003290 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003291 }
John Kessenich140f3df2015-06-26 16:58:36 -06003292
John Kessenich32cfd492016-02-02 12:37:46 -07003293 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003294}
3295
John Kessenich7a53f762016-01-20 11:19:27 -07003296// Create a unary operation on a matrix
3297spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3298{
3299 // Handle unary operations vector by vector.
3300 // The result type is the same type as the original type.
3301 // The algorithm is to:
3302 // - break the matrix into vectors
3303 // - apply the operation to each vector
3304 // - make a matrix out the vector results
3305
3306 // get the types sorted out
3307 int numCols = builder.getNumColumns(operand);
3308 int numRows = builder.getNumRows(operand);
3309 spv::Id scalarType = builder.getScalarTypeId(typeId);
3310 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3311 std::vector<spv::Id> results;
3312
3313 // do each vector op
3314 for (int c = 0; c < numCols; ++c) {
3315 std::vector<unsigned int> indexes;
3316 indexes.push_back(c);
3317 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3318 results.push_back(builder.createUnaryOp(op, vecType, vec));
3319 builder.setPrecision(results.back(), precision);
3320 }
3321
3322 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003323 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003324}
3325
John Kessenich140f3df2015-06-26 16:58:36 -06003326spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3327{
3328 spv::Op convOp = spv::OpNop;
3329 spv::Id zero = 0;
3330 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003331 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003332
3333 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3334
3335 switch (op) {
3336 case glslang::EOpConvIntToBool:
3337 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 case glslang::EOpConvInt64ToBool:
3339 case glslang::EOpConvUint64ToBool:
3340 zero = (op == glslang::EOpConvInt64ToBool ||
3341 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003342 zero = makeSmearedConstant(zero, vectorSize);
3343 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3344
3345 case glslang::EOpConvFloatToBool:
3346 zero = builder.makeFloatConstant(0.0F);
3347 zero = makeSmearedConstant(zero, vectorSize);
3348 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3349
3350 case glslang::EOpConvDoubleToBool:
3351 zero = builder.makeDoubleConstant(0.0);
3352 zero = makeSmearedConstant(zero, vectorSize);
3353 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3354
3355 case glslang::EOpConvBoolToFloat:
3356 convOp = spv::OpSelect;
3357 zero = builder.makeFloatConstant(0.0);
3358 one = builder.makeFloatConstant(1.0);
3359 break;
3360 case glslang::EOpConvBoolToDouble:
3361 convOp = spv::OpSelect;
3362 zero = builder.makeDoubleConstant(0.0);
3363 one = builder.makeDoubleConstant(1.0);
3364 break;
3365 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003366 case glslang::EOpConvBoolToInt64:
3367 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3368 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003369 convOp = spv::OpSelect;
3370 break;
3371 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003372 case glslang::EOpConvBoolToUint64:
3373 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3374 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003375 convOp = spv::OpSelect;
3376 break;
3377
3378 case glslang::EOpConvIntToFloat:
3379 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003380 case glslang::EOpConvInt64ToFloat:
3381 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003382 convOp = spv::OpConvertSToF;
3383 break;
3384
3385 case glslang::EOpConvUintToFloat:
3386 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003387 case glslang::EOpConvUint64ToFloat:
3388 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003389 convOp = spv::OpConvertUToF;
3390 break;
3391
3392 case glslang::EOpConvDoubleToFloat:
3393 case glslang::EOpConvFloatToDouble:
3394 convOp = spv::OpFConvert;
3395 break;
3396
3397 case glslang::EOpConvFloatToInt:
3398 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003399 case glslang::EOpConvFloatToInt64:
3400 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003401 convOp = spv::OpConvertFToS;
3402 break;
3403
3404 case glslang::EOpConvUintToInt:
3405 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003406 case glslang::EOpConvUint64ToInt64:
3407 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003408 if (builder.isInSpecConstCodeGenMode()) {
3409 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003410 zero = (op == glslang::EOpConvUintToInt64 ||
3411 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003412 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003413 // Use OpIAdd, instead of OpBitcast to do the conversion when
3414 // generating for OpSpecConstantOp instruction.
3415 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3416 }
3417 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003418 convOp = spv::OpBitcast;
3419 break;
3420
3421 case glslang::EOpConvFloatToUint:
3422 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003423 case glslang::EOpConvFloatToUint64:
3424 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003425 convOp = spv::OpConvertFToU;
3426 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003427
3428 case glslang::EOpConvIntToInt64:
3429 case glslang::EOpConvInt64ToInt:
3430 convOp = spv::OpSConvert;
3431 break;
3432
3433 case glslang::EOpConvUintToUint64:
3434 case glslang::EOpConvUint64ToUint:
3435 convOp = spv::OpUConvert;
3436 break;
3437
3438 case glslang::EOpConvIntToUint64:
3439 case glslang::EOpConvInt64ToUint:
3440 case glslang::EOpConvUint64ToInt:
3441 case glslang::EOpConvUintToInt64:
3442 // OpSConvert/OpUConvert + OpBitCast
3443 switch (op) {
3444 case glslang::EOpConvIntToUint64:
3445 convOp = spv::OpSConvert;
3446 type = builder.makeIntType(64);
3447 break;
3448 case glslang::EOpConvInt64ToUint:
3449 convOp = spv::OpSConvert;
3450 type = builder.makeIntType(32);
3451 break;
3452 case glslang::EOpConvUint64ToInt:
3453 convOp = spv::OpUConvert;
3454 type = builder.makeUintType(32);
3455 break;
3456 case glslang::EOpConvUintToInt64:
3457 convOp = spv::OpUConvert;
3458 type = builder.makeUintType(64);
3459 break;
3460 default:
3461 assert(0);
3462 break;
3463 }
3464
3465 if (vectorSize > 0)
3466 type = builder.makeVectorType(type, vectorSize);
3467
3468 operand = builder.createUnaryOp(convOp, type, operand);
3469
3470 if (builder.isInSpecConstCodeGenMode()) {
3471 // Build zero scalar or vector for OpIAdd.
3472 zero = (op == glslang::EOpConvIntToUint64 ||
3473 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3474 zero = makeSmearedConstant(zero, vectorSize);
3475 // Use OpIAdd, instead of OpBitcast to do the conversion when
3476 // generating for OpSpecConstantOp instruction.
3477 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3478 }
3479 // For normal run-time conversion instruction, use OpBitcast.
3480 convOp = spv::OpBitcast;
3481 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 default:
3483 break;
3484 }
3485
3486 spv::Id result = 0;
3487 if (convOp == spv::OpNop)
3488 return result;
3489
3490 if (convOp == spv::OpSelect) {
3491 zero = makeSmearedConstant(zero, vectorSize);
3492 one = makeSmearedConstant(one, vectorSize);
3493 result = builder.createTriOp(convOp, destType, operand, one, zero);
3494 } else
3495 result = builder.createUnaryOp(convOp, destType, operand);
3496
John Kessenich32cfd492016-02-02 12:37:46 -07003497 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003498}
3499
3500spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3501{
3502 if (vectorSize == 0)
3503 return constant;
3504
3505 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3506 std::vector<spv::Id> components;
3507 for (int c = 0; c < vectorSize; ++c)
3508 components.push_back(constant);
3509 return builder.makeCompositeConstant(vectorTypeId, components);
3510}
3511
John Kessenich426394d2015-07-23 10:22:48 -06003512// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003513spv::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 -06003514{
3515 spv::Op opCode = spv::OpNop;
3516
3517 switch (op) {
3518 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003519 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003520 opCode = spv::OpAtomicIAdd;
3521 break;
3522 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003523 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003524 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003525 break;
3526 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003527 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003528 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003529 break;
3530 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003531 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003532 opCode = spv::OpAtomicAnd;
3533 break;
3534 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003535 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003536 opCode = spv::OpAtomicOr;
3537 break;
3538 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003539 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003540 opCode = spv::OpAtomicXor;
3541 break;
3542 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003543 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003544 opCode = spv::OpAtomicExchange;
3545 break;
3546 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003547 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003548 opCode = spv::OpAtomicCompareExchange;
3549 break;
3550 case glslang::EOpAtomicCounterIncrement:
3551 opCode = spv::OpAtomicIIncrement;
3552 break;
3553 case glslang::EOpAtomicCounterDecrement:
3554 opCode = spv::OpAtomicIDecrement;
3555 break;
3556 case glslang::EOpAtomicCounter:
3557 opCode = spv::OpAtomicLoad;
3558 break;
3559 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003560 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003561 break;
3562 }
3563
3564 // Sort out the operands
3565 // - mapping from glslang -> SPV
3566 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003567 // - compare-exchange swaps the value and comparator
3568 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003569 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3570 auto opIt = operands.begin(); // walk the glslang operands
3571 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003572 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3573 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3574 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003575 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3576 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003577 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003578 spvAtomicOperands.push_back(*(opIt + 1));
3579 spvAtomicOperands.push_back(*opIt);
3580 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003581 }
John Kessenich426394d2015-07-23 10:22:48 -06003582
John Kessenich3e60a6f2015-09-14 22:45:16 -06003583 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003584 for (; opIt != operands.end(); ++opIt)
3585 spvAtomicOperands.push_back(*opIt);
3586
3587 return builder.createOp(opCode, typeId, spvAtomicOperands);
3588}
3589
John Kessenich91cef522016-05-05 16:45:40 -06003590// Create group invocation operations.
3591spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3592{
3593 builder.addCapability(spv::CapabilityGroups);
3594
3595 std::vector<spv::Id> operands;
3596 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3597 operands.push_back(operand);
3598
3599 switch (op) {
3600 case glslang::EOpAnyInvocation:
3601 case glslang::EOpAllInvocations:
3602 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3603
3604 case glslang::EOpAllInvocationsEqual:
3605 {
3606 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3607 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3608
3609 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3610 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3611 }
3612 default:
3613 logger->missingFunctionality("invocation operation");
3614 return spv::NoResult;
3615 }
3616}
3617
John Kessenich5e4b1242015-08-06 22:53:06 -06003618spv::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 -06003619{
Rex Xu8ff43de2016-04-22 16:51:45 +08003620 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003621 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3622
John Kessenich140f3df2015-06-26 16:58:36 -06003623 spv::Op opCode = spv::OpNop;
3624 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003625 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003626 spv::Id typeId0 = 0;
3627 if (consumedOperands > 0)
3628 typeId0 = builder.getTypeId(operands[0]);
3629 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003630
3631 switch (op) {
3632 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003633 if (isFloat)
3634 libCall = spv::GLSLstd450FMin;
3635 else if (isUnsigned)
3636 libCall = spv::GLSLstd450UMin;
3637 else
3638 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003639 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
3644 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003645 if (isFloat)
3646 libCall = spv::GLSLstd450FMax;
3647 else if (isUnsigned)
3648 libCall = spv::GLSLstd450UMax;
3649 else
3650 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003651 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003652 break;
3653 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003654 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
3656 case glslang::EOpDot:
3657 opCode = spv::OpDot;
3658 break;
3659 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003661 break;
3662
3663 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003664 if (isFloat)
3665 libCall = spv::GLSLstd450FClamp;
3666 else if (isUnsigned)
3667 libCall = spv::GLSLstd450UClamp;
3668 else
3669 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003670 builder.promoteScalar(precision, operands.front(), operands[1]);
3671 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003672 break;
3673 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003674 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3675 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003676 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003677 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003678 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003679 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003680 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003681 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003682 break;
3683 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003684 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003685 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003686 break;
3687 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003688 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003689 builder.promoteScalar(precision, operands[0], operands[2]);
3690 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003691 break;
3692
3693 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003694 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 break;
3696 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003698 break;
3699 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003700 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003703 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 break;
3705 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003706 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003707 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003708 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003709 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003710 libCall = spv::GLSLstd450InterpolateAtSample;
3711 break;
3712 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003713 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003714 libCall = spv::GLSLstd450InterpolateAtOffset;
3715 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003716 case glslang::EOpAddCarry:
3717 opCode = spv::OpIAddCarry;
3718 typeId = builder.makeStructResultType(typeId0, typeId0);
3719 consumedOperands = 2;
3720 break;
3721 case glslang::EOpSubBorrow:
3722 opCode = spv::OpISubBorrow;
3723 typeId = builder.makeStructResultType(typeId0, typeId0);
3724 consumedOperands = 2;
3725 break;
3726 case glslang::EOpUMulExtended:
3727 opCode = spv::OpUMulExtended;
3728 typeId = builder.makeStructResultType(typeId0, typeId0);
3729 consumedOperands = 2;
3730 break;
3731 case glslang::EOpIMulExtended:
3732 opCode = spv::OpSMulExtended;
3733 typeId = builder.makeStructResultType(typeId0, typeId0);
3734 consumedOperands = 2;
3735 break;
3736 case glslang::EOpBitfieldExtract:
3737 if (isUnsigned)
3738 opCode = spv::OpBitFieldUExtract;
3739 else
3740 opCode = spv::OpBitFieldSExtract;
3741 break;
3742 case glslang::EOpBitfieldInsert:
3743 opCode = spv::OpBitFieldInsert;
3744 break;
3745
3746 case glslang::EOpFma:
3747 libCall = spv::GLSLstd450Fma;
3748 break;
3749 case glslang::EOpFrexp:
3750 libCall = spv::GLSLstd450FrexpStruct;
3751 if (builder.getNumComponents(operands[0]) == 1)
3752 frexpIntType = builder.makeIntegerType(32, true);
3753 else
3754 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3755 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3756 consumedOperands = 1;
3757 break;
3758 case glslang::EOpLdexp:
3759 libCall = spv::GLSLstd450Ldexp;
3760 break;
3761
Rex Xu574ab042016-04-14 16:53:07 +08003762 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003763 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003764 libCall = spv::GLSLstd450Bad;
3765 break;
3766
John Kessenich140f3df2015-06-26 16:58:36 -06003767 default:
3768 return 0;
3769 }
3770
3771 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003772 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003773 // Use an extended instruction from the standard library.
3774 // Construct the call arguments, without modifying the original operands vector.
3775 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3776 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003777 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003778 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003779 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003780 case 0:
3781 // should all be handled by visitAggregate and createNoArgOperation
3782 assert(0);
3783 return 0;
3784 case 1:
3785 // should all be handled by createUnaryOperation
3786 assert(0);
3787 return 0;
3788 case 2:
3789 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3790 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003791 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003792 // anything 3 or over doesn't have l-value operands, so all should be consumed
3793 assert(consumedOperands == operands.size());
3794 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003795 break;
3796 }
3797 }
3798
John Kessenich55e7d112015-11-15 21:33:39 -07003799 // Decode the return types that were structures
3800 switch (op) {
3801 case glslang::EOpAddCarry:
3802 case glslang::EOpSubBorrow:
3803 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3804 id = builder.createCompositeExtract(id, typeId0, 0);
3805 break;
3806 case glslang::EOpUMulExtended:
3807 case glslang::EOpIMulExtended:
3808 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3809 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3810 break;
3811 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003812 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003813 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3814 id = builder.createCompositeExtract(id, typeId0, 0);
3815 break;
3816 default:
3817 break;
3818 }
3819
John Kessenich32cfd492016-02-02 12:37:46 -07003820 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003821}
3822
3823// Intrinsics with no arguments, no return value, and no precision.
3824spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3825{
3826 // TODO: get the barrier operands correct
3827
3828 switch (op) {
3829 case glslang::EOpEmitVertex:
3830 builder.createNoResultOp(spv::OpEmitVertex);
3831 return 0;
3832 case glslang::EOpEndPrimitive:
3833 builder.createNoResultOp(spv::OpEndPrimitive);
3834 return 0;
3835 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003836 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3837 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 return 0;
3839 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003841 return 0;
3842 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003843 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 return 0;
3845 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003846 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003847 return 0;
3848 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003849 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003850 return 0;
3851 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003852 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003853 return 0;
3854 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003855 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003856 return 0;
3857 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003858 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003859 return 0;
3860 }
3861}
3862
3863spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3864{
John Kessenich2f273362015-07-18 22:34:27 -06003865 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003866 spv::Id id;
3867 if (symbolValues.end() != iter) {
3868 id = iter->second;
3869 return id;
3870 }
3871
3872 // it was not found, create it
3873 id = createSpvVariable(symbol);
3874 symbolValues[symbol->getId()] = id;
3875
3876 if (! symbol->getType().isStruct()) {
3877 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003878 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003879 if (symbol->getType().getQualifier().hasSpecConstantId())
3880 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003881 if (symbol->getQualifier().hasLocation())
3882 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3883 if (symbol->getQualifier().hasIndex())
3884 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3885 if (symbol->getQualifier().hasComponent())
3886 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3887 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003888 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003889 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003891 if (symbol->getQualifier().hasXfbBuffer())
3892 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3893 if (symbol->getQualifier().hasXfbOffset())
3894 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3895 }
3896 }
3897
John Kesseniche0b6cad2015-12-24 10:30:13 -07003898 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003899 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003900 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003901 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003902 }
John Kessenich140f3df2015-06-26 16:58:36 -06003903 if (symbol->getQualifier().hasSet())
3904 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003905 else if (IsDescriptorResource(symbol->getType())) {
3906 // default to 0
3907 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3908 }
John Kessenich140f3df2015-06-26 16:58:36 -06003909 if (symbol->getQualifier().hasBinding())
3910 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003911 if (symbol->getQualifier().hasAttachment())
3912 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003913 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003914 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003915 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003916 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003917 if (symbol->getQualifier().hasXfbBuffer())
3918 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3919 }
3920
Rex Xu1da878f2016-02-21 20:59:01 +08003921 if (symbol->getType().isImage()) {
3922 std::vector<spv::Decoration> memory;
3923 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3924 for (unsigned int i = 0; i < memory.size(); ++i)
3925 addDecoration(id, memory[i]);
3926 }
3927
John Kessenich140f3df2015-06-26 16:58:36 -06003928 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003929 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003931 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003932
John Kessenich140f3df2015-06-26 16:58:36 -06003933 return id;
3934}
3935
John Kessenich55e7d112015-11-15 21:33:39 -07003936// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003937void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3938{
3939 if (dec != spv::BadValue)
3940 builder.addDecoration(id, dec);
3941}
3942
John Kessenich55e7d112015-11-15 21:33:39 -07003943// If 'dec' is valid, add a one-operand decoration to an object
3944void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3945{
3946 if (dec != spv::BadValue)
3947 builder.addDecoration(id, dec, value);
3948}
3949
3950// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003951void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3952{
3953 if (dec != spv::BadValue)
3954 builder.addMemberDecoration(id, (unsigned)member, dec);
3955}
3956
John Kessenich92187592016-02-01 13:45:25 -07003957// If 'dec' is valid, add a one-operand decoration to a struct member
3958void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3959{
3960 if (dec != spv::BadValue)
3961 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3962}
3963
John Kessenich55e7d112015-11-15 21:33:39 -07003964// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003965// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003966//
3967// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3968//
3969// Recursively walk the nodes. The nodes form a tree whose leaves are
3970// regular constants, which themselves are trees that createSpvConstant()
3971// recursively walks. So, this function walks the "top" of the tree:
3972// - emit specialization constant-building instructions for specConstant
3973// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003974spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003975{
John Kessenich7cc0e282016-03-20 00:46:02 -06003976 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003977
qining4f4bb812016-04-03 23:55:17 -04003978 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003979 if (! node.getQualifier().specConstant) {
3980 // hand off to the non-spec-constant path
3981 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3982 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003983 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003984 nextConst, false);
3985 }
3986
3987 // We now know we have a specialization constant to build
3988
qining4f4bb812016-04-03 23:55:17 -04003989 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3990 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3991 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3992 std::vector<spv::Id> dimConstId;
3993 for (int dim = 0; dim < 3; ++dim) {
3994 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3995 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3996 if (specConst)
3997 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3998 }
3999 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4000 }
4001
4002 // An AST node labelled as specialization constant should be a symbol node.
4003 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4004 if (auto* sn = node.getAsSymbolNode()) {
4005 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004006 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4007 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4008 // will set the builder into spec constant op instruction generating mode.
4009 sub_tree->traverse(this);
4010 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004011 } else if (auto* const_union_array = &sn->getConstArray()){
4012 int nextConst = 0;
4013 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004014 }
4015 }
qining4f4bb812016-04-03 23:55:17 -04004016
4017 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4018 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004019 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004020 exit(1);
4021 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004022}
4023
John Kessenich140f3df2015-06-26 16:58:36 -06004024// Use 'consts' as the flattened glslang source of scalar constants to recursively
4025// build the aggregate SPIR-V constant.
4026//
4027// If there are not enough elements present in 'consts', 0 will be substituted;
4028// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4029//
qining08408382016-03-21 09:51:37 -04004030spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004031{
4032 // vector of constants for SPIR-V
4033 std::vector<spv::Id> spvConsts;
4034
4035 // Type is used for struct and array constants
4036 spv::Id typeId = convertGlslangToSpvType(glslangType);
4037
4038 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004039 glslang::TType elementType(glslangType, 0);
4040 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004041 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004042 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004043 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004044 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004045 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004046 } else if (glslangType.getStruct()) {
4047 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4048 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004049 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004050 } else if (glslangType.isVector()) {
4051 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4052 bool zero = nextConst >= consts.size();
4053 switch (glslangType.getBasicType()) {
4054 case glslang::EbtInt:
4055 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4056 break;
4057 case glslang::EbtUint:
4058 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4059 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004060 case glslang::EbtInt64:
4061 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4062 break;
4063 case glslang::EbtUint64:
4064 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4065 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 case glslang::EbtFloat:
4067 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4068 break;
4069 case glslang::EbtDouble:
4070 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4071 break;
4072 case glslang::EbtBool:
4073 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4074 break;
4075 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004076 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078 }
4079 ++nextConst;
4080 }
4081 } else {
4082 // we have a non-aggregate (scalar) constant
4083 bool zero = nextConst >= consts.size();
4084 spv::Id scalar = 0;
4085 switch (glslangType.getBasicType()) {
4086 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004087 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004090 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004092 case glslang::EbtInt64:
4093 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4094 break;
4095 case glslang::EbtUint64:
4096 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4097 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004099 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004100 break;
4101 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004102 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004103 break;
4104 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004105 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004106 break;
4107 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004108 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004109 break;
4110 }
4111 ++nextConst;
4112 return scalar;
4113 }
4114
4115 return builder.makeCompositeConstant(typeId, spvConsts);
4116}
4117
John Kessenich7c1aa102015-10-15 13:29:11 -06004118// Return true if the node is a constant or symbol whose reading has no
4119// non-trivial observable cost or effect.
4120bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4121{
4122 // don't know what this is
4123 if (node == nullptr)
4124 return false;
4125
4126 // a constant is safe
4127 if (node->getAsConstantUnion() != nullptr)
4128 return true;
4129
4130 // not a symbol means non-trivial
4131 if (node->getAsSymbolNode() == nullptr)
4132 return false;
4133
4134 // a symbol, depends on what's being read
4135 switch (node->getType().getQualifier().storage) {
4136 case glslang::EvqTemporary:
4137 case glslang::EvqGlobal:
4138 case glslang::EvqIn:
4139 case glslang::EvqInOut:
4140 case glslang::EvqConst:
4141 case glslang::EvqConstReadOnly:
4142 case glslang::EvqUniform:
4143 return true;
4144 default:
4145 return false;
4146 }
4147}
4148
4149// A node is trivial if it is a single operation with no side effects.
4150// Error on the side of saying non-trivial.
4151// Return true if trivial.
4152bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4153{
4154 if (node == nullptr)
4155 return false;
4156
4157 // symbols and constants are trivial
4158 if (isTrivialLeaf(node))
4159 return true;
4160
4161 // otherwise, it needs to be a simple operation or one or two leaf nodes
4162
4163 // not a simple operation
4164 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4165 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4166 if (binaryNode == nullptr && unaryNode == nullptr)
4167 return false;
4168
4169 // not on leaf nodes
4170 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4171 return false;
4172
4173 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4174 return false;
4175 }
4176
4177 switch (node->getAsOperator()->getOp()) {
4178 case glslang::EOpLogicalNot:
4179 case glslang::EOpConvIntToBool:
4180 case glslang::EOpConvUintToBool:
4181 case glslang::EOpConvFloatToBool:
4182 case glslang::EOpConvDoubleToBool:
4183 case glslang::EOpEqual:
4184 case glslang::EOpNotEqual:
4185 case glslang::EOpLessThan:
4186 case glslang::EOpGreaterThan:
4187 case glslang::EOpLessThanEqual:
4188 case glslang::EOpGreaterThanEqual:
4189 case glslang::EOpIndexDirect:
4190 case glslang::EOpIndexDirectStruct:
4191 case glslang::EOpLogicalXor:
4192 case glslang::EOpAny:
4193 case glslang::EOpAll:
4194 return true;
4195 default:
4196 return false;
4197 }
4198}
4199
4200// Emit short-circuiting code, where 'right' is never evaluated unless
4201// the left side is true (for &&) or false (for ||).
4202spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4203{
4204 spv::Id boolTypeId = builder.makeBoolType();
4205
4206 // emit left operand
4207 builder.clearAccessChain();
4208 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004209 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004210
4211 // Operands to accumulate OpPhi operands
4212 std::vector<spv::Id> phiOperands;
4213 // accumulate left operand's phi information
4214 phiOperands.push_back(leftId);
4215 phiOperands.push_back(builder.getBuildPoint()->getId());
4216
4217 // Make the two kinds of operation symmetric with a "!"
4218 // || => emit "if (! left) result = right"
4219 // && => emit "if ( left) result = right"
4220 //
4221 // TODO: this runtime "not" for || could be avoided by adding functionality
4222 // to 'builder' to have an "else" without an "then"
4223 if (op == glslang::EOpLogicalOr)
4224 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4225
4226 // make an "if" based on the left value
4227 spv::Builder::If ifBuilder(leftId, builder);
4228
4229 // emit right operand as the "then" part of the "if"
4230 builder.clearAccessChain();
4231 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004232 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004233
4234 // accumulate left operand's phi information
4235 phiOperands.push_back(rightId);
4236 phiOperands.push_back(builder.getBuildPoint()->getId());
4237
4238 // finish the "if"
4239 ifBuilder.makeEndIf();
4240
4241 // phi together the two results
4242 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4243}
4244
John Kessenich140f3df2015-06-26 16:58:36 -06004245}; // end anonymous namespace
4246
4247namespace glslang {
4248
John Kessenich68d78fd2015-07-12 19:28:10 -06004249void GetSpirvVersion(std::string& version)
4250{
John Kessenich9e55f632015-07-15 10:03:39 -06004251 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004252 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004253 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004254 version = buf;
4255}
4256
John Kessenich140f3df2015-06-26 16:58:36 -06004257// Write SPIR-V out to a binary file
4258void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4259{
4260 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004261 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004262 for (int i = 0; i < (int)spirv.size(); ++i) {
4263 unsigned int word = spirv[i];
4264 out.write((const char*)&word, 4);
4265 }
4266 out.close();
4267}
4268
4269//
4270// Set up the glslang traversal
4271//
4272void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4273{
Lei Zhang17535f72016-05-04 15:55:59 -04004274 spv::SpvBuildLogger logger;
4275 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004276}
4277
Lei Zhang17535f72016-05-04 15:55:59 -04004278void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004279{
John Kessenich140f3df2015-06-26 16:58:36 -06004280 TIntermNode* root = intermediate.getTreeRoot();
4281
4282 if (root == 0)
4283 return;
4284
4285 glslang::GetThreadPoolAllocator().push();
4286
Lei Zhang17535f72016-05-04 15:55:59 -04004287 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004288
4289 root->traverse(&it);
4290
4291 it.dumpSpv(spirv);
4292
4293 glslang::GetThreadPoolAllocator().pop();
4294}
4295
4296}; // end namespace glslang