blob: 470ed25372b9ad09de21b260f3e7faa5ebdd8436 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
Rex Xu9d93a232016-05-05 12:30:44 +080046#ifdef AMD_EXTENSIONS
47 #include "GLSL.ext.AMD.h"
48#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060049}
John Kessenich140f3df2015-06-26 16:58:36 -060050
51// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020052#include "../glslang/MachineIndependent/localintermediate.h"
53#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060054#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050055#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060056
John Kessenich140f3df2015-06-26 16:58:36 -060057#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050058#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040059#include <list>
60#include <map>
61#include <stack>
62#include <string>
63#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060064
65namespace {
66
John Kessenich55e7d112015-11-15 21:33:39 -070067// For low-order part of the generator's magic number. Bump up
68// when there is a change in the style (e.g., if SSA form changes,
69// or a different instruction sequence to do something gets used).
70const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060071
qining4c912612016-04-01 10:35:16 -040072namespace {
73class SpecConstantOpModeGuard {
74public:
75 SpecConstantOpModeGuard(spv::Builder* builder)
76 : builder_(builder) {
77 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040078 }
79 ~SpecConstantOpModeGuard() {
80 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
81 : builder_->setToNormalCodeGenMode();
82 }
qining40887662016-04-03 22:20:42 -040083 void turnOnSpecConstantOpMode() {
84 builder_->setToSpecConstCodeGenMode();
85 }
qining4c912612016-04-01 10:35:16 -040086
87private:
88 spv::Builder* builder_;
89 bool previous_flag_;
90};
91}
92
John Kessenich140f3df2015-06-26 16:58:36 -060093//
94// The main holder of information for translating glslang to SPIR-V.
95//
96// Derives from the AST walking base class.
97//
98class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
99public:
Lei Zhang17535f72016-05-04 15:55:59 -0400100 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600101 virtual ~TGlslangToSpvTraverser();
102
103 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
104 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
105 void visitConstantUnion(glslang::TIntermConstantUnion*);
106 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
107 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
108 void visitSymbol(glslang::TIntermSymbol* symbol);
109 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
110 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
111 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
112
John Kessenich7ba63412015-12-20 17:37:07 -0700113 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600114
115protected:
Rex Xubbceed72016-05-21 09:40:44 +0800116 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100117 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700118 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600119 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
120 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600121 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
122 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
123 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600124 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700125 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600126 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
127 glslang::TLayoutPacking, const glslang::TQualifier&);
128 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
129 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700130 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700131 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800132 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700133 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700134 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
135 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
136 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100137 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600138
139 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
140 void makeFunctions(const glslang::TIntermSequence&);
141 void makeGlobalInitializers(const glslang::TIntermSequence&);
142 void visitFunctions(const glslang::TIntermSequence&);
143 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800144 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600145 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
146 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
148
qining25262b32016-05-06 17:25:16 -0400149 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
150 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
151 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
152 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800153 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800156 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600157 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800158 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600159 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
160 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700161 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700163 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400164 spv::Id createSpvConstant(const glslang::TIntermTyped&);
165 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600166 bool isTrivialLeaf(const glslang::TIntermTyped* node);
167 bool isTrivial(const glslang::TIntermTyped* node);
168 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800169 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600170
171 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700172 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600173 int sequenceDepth;
174
Lei Zhang17535f72016-05-04 15:55:59 -0400175 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400176
John Kessenich140f3df2015-06-26 16:58:36 -0600177 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
178 spv::Builder builder;
179 bool inMain;
180 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700181 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 -0700182 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600183 const glslang::TIntermediate* glslangIntermediate;
184 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800185 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600186
John Kessenich2f273362015-07-18 22:34:27 -0600187 std::unordered_map<int, spv::Id> symbolValues;
188 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
189 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700190 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600191 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 -0600192 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600193};
194
195//
196// Helper functions for translating glslang representations to SPIR-V enumerants.
197//
198
199// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700200spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600201{
John Kessenich66e2faf2016-03-12 18:34:36 -0700202 switch (source) {
203 case glslang::EShSourceGlsl:
204 switch (profile) {
205 case ENoProfile:
206 case ECoreProfile:
207 case ECompatibilityProfile:
208 return spv::SourceLanguageGLSL;
209 case EEsProfile:
210 return spv::SourceLanguageESSL;
211 default:
212 return spv::SourceLanguageUnknown;
213 }
214 case glslang::EShSourceHlsl:
215 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 default:
217 return spv::SourceLanguageUnknown;
218 }
219}
220
221// Translate glslang language (stage) to SPIR-V execution model.
222spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
223{
224 switch (stage) {
225 case EShLangVertex: return spv::ExecutionModelVertex;
226 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
227 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
228 case EShLangGeometry: return spv::ExecutionModelGeometry;
229 case EShLangFragment: return spv::ExecutionModelFragment;
230 case EShLangCompute: return spv::ExecutionModelGLCompute;
231 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700232 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600233 return spv::ExecutionModelFragment;
234 }
235}
236
237// Translate glslang type to SPIR-V storage class.
238spv::StorageClass TranslateStorageClass(const glslang::TType& type)
239{
240 if (type.getQualifier().isPipeInput())
241 return spv::StorageClassInput;
242 else if (type.getQualifier().isPipeOutput())
243 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700244 else if (type.getBasicType() == glslang::EbtSampler)
245 return spv::StorageClassUniformConstant;
246 else if (type.getBasicType() == glslang::EbtAtomicUint)
247 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600248 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700249 if (type.getQualifier().layoutPushConstant)
250 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600251 if (type.getBasicType() == glslang::EbtBlock)
252 return spv::StorageClassUniform;
253 else
254 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600255 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600256 } else {
257 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700258 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
259 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
261 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::StorageClassFunction;
265 }
266 }
267}
268
269// Translate glslang sampler type to SPIR-V dimensionality.
270spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
271{
272 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700273 case glslang::Esd1D: return spv::Dim1D;
274 case glslang::Esd2D: return spv::Dim2D;
275 case glslang::Esd3D: return spv::Dim3D;
276 case glslang::EsdCube: return spv::DimCube;
277 case glslang::EsdRect: return spv::DimRect;
278 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700279 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600280 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700281 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600282 return spv::Dim2D;
283 }
284}
285
286// Translate glslang type to SPIR-V precision decorations.
287spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
288{
289 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700290 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600291 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 default:
293 return spv::NoPrecision;
294 }
295}
296
297// Translate glslang type to SPIR-V block decorations.
298spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
299{
300 if (type.getBasicType() == glslang::EbtBlock) {
301 switch (type.getQualifier().storage) {
302 case glslang::EvqUniform: return spv::DecorationBlock;
303 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
304 case glslang::EvqVaryingIn: return spv::DecorationBlock;
305 case glslang::EvqVaryingOut: return spv::DecorationBlock;
306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 break;
309 }
310 }
311
John Kessenich4016e382016-07-15 11:53:56 -0600312 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600313}
314
Rex Xu1da878f2016-02-21 20:59:01 +0800315// Translate glslang type to SPIR-V memory decorations.
316void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
317{
318 if (qualifier.coherent)
319 memory.push_back(spv::DecorationCoherent);
320 if (qualifier.volatil)
321 memory.push_back(spv::DecorationVolatile);
322 if (qualifier.restrict)
323 memory.push_back(spv::DecorationRestrict);
324 if (qualifier.readonly)
325 memory.push_back(spv::DecorationNonWritable);
326 if (qualifier.writeonly)
327 memory.push_back(spv::DecorationNonReadable);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700331spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElmRowMajor:
336 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700339 default:
340 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 } else {
344 switch (type.getBasicType()) {
345 default:
John Kessenich4016e382016-07-15 11:53:56 -0600346 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 case glslang::EbtBlock:
349 switch (type.getQualifier().storage) {
350 case glslang::EvqUniform:
351 case glslang::EvqBuffer:
352 switch (type.getQualifier().layoutPacking) {
353 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 case glslang::EvqVaryingIn:
359 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700363 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 }
367 }
368}
369
370// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600371// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700372// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800373spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
Rex Xubbceed72016-05-21 09:40:44 +0800375 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700379 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800382#ifdef AMD_EXTENSIONS
383 else if (qualifier.explicitInterp)
384 return spv::DecorationExplicitInterpAMD;
385#endif
Rex Xubbceed72016-05-21 09:40:44 +0800386 else
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388}
389
390// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600391// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800392// should be applied.
393spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
394{
395 if (qualifier.patch)
396 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700399 else if (qualifier.sample) {
400 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700402 } else
John Kessenich4016e382016-07-15 11:53:56 -0600403 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600404}
405
John Kessenich92187592016-02-01 13:45:25 -0700406// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600408{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationInvariant;
411 else
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600413}
414
qining9220dbb2016-05-04 17:34:38 -0400415// If glslang type is noContraction, return SPIR-V NoContraction decoration.
416spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
417{
418 if (qualifier.noContraction)
419 return spv::DecorationNoContraction;
420 else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400422}
423
David Netoa901ffe2016-06-08 14:11:40 +0100424// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
425// associated capabilities when required. For some built-in variables, a capability
426// is generated only when using the variable in an executable instruction, but not when
427// just declaring a struct member variable with it. This is true for PointSize,
428// ClipDistance, and CullDistance.
429spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600430{
431 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700432 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600433 // Defer adding the capability until the built-in is actually used.
434 if (! memberDeclaration) {
435 switch (glslangIntermediate->getStage()) {
436 case EShLangGeometry:
437 builder.addCapability(spv::CapabilityGeometryPointSize);
438 break;
439 case EShLangTessControl:
440 case EShLangTessEvaluation:
441 builder.addCapability(spv::CapabilityTessellationPointSize);
442 break;
443 default:
444 break;
445 }
John Kessenich92187592016-02-01 13:45:25 -0700446 }
447 return spv::BuiltInPointSize;
448
John Kessenichebb50532016-05-16 19:22:05 -0600449 // These *Distance capabilities logically belong here, but if the member is declared and
450 // then never used, consumers of SPIR-V prefer the capability not be declared.
451 // They are now generated when used, rather than here when declared.
452 // Potentially, the specification should be more clear what the minimum
453 // use needed is to trigger the capability.
454 //
John Kessenich92187592016-02-01 13:45:25 -0700455 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100456 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600457 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700458 return spv::BuiltInClipDistance;
459
460 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100461 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600462 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700463 return spv::BuiltInCullDistance;
464
465 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500466 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700467 return spv::BuiltInViewportIndex;
468
John Kessenich5e801132016-02-15 11:09:46 -0700469 case glslang::EbvSampleId:
470 builder.addCapability(spv::CapabilitySampleRateShading);
471 return spv::BuiltInSampleId;
472
473 case glslang::EbvSamplePosition:
474 builder.addCapability(spv::CapabilitySampleRateShading);
475 return spv::BuiltInSamplePosition;
476
477 case glslang::EbvSampleMask:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSampleMask;
480
John Kessenich78a45572016-07-08 14:05:15 -0600481 case glslang::EbvLayer:
482 builder.addCapability(spv::CapabilityGeometry);
483 return spv::BuiltInLayer;
484
John Kessenich140f3df2015-06-26 16:58:36 -0600485 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600486 case glslang::EbvVertexId: return spv::BuiltInVertexId;
487 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700488 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
489 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600490 case glslang::EbvBaseVertex:
491 case glslang::EbvBaseInstance:
492 case glslang::EbvDrawId:
493 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600494 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600495 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
497 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
499 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
500 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
501 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
502 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
503 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
504 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600505 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
506 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
507 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
508 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
509 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
510 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
511 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
512 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800513 case glslang::EbvSubGroupSize:
514 case glslang::EbvSubGroupInvocation:
515 case glslang::EbvSubGroupEqMask:
516 case glslang::EbvSubGroupGeMask:
517 case glslang::EbvSubGroupGtMask:
518 case glslang::EbvSubGroupLeMask:
519 case glslang::EbvSubGroupLtMask:
520 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600521 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600522 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800523#ifdef AMD_EXTENSIONS
524 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
525 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
526 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
527 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
528 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
529 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
530 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
531#endif
John Kessenich4016e382016-07-15 11:53:56 -0600532 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600533 }
534}
535
Rex Xufc618912015-09-09 16:42:49 +0800536// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700537spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800538{
539 assert(type.getBasicType() == glslang::EbtSampler);
540
John Kessenich5d0fa972016-02-15 11:57:00 -0700541 // Check for capabilities
542 switch (type.getQualifier().layoutFormat) {
543 case glslang::ElfRg32f:
544 case glslang::ElfRg16f:
545 case glslang::ElfR11fG11fB10f:
546 case glslang::ElfR16f:
547 case glslang::ElfRgba16:
548 case glslang::ElfRgb10A2:
549 case glslang::ElfRg16:
550 case glslang::ElfRg8:
551 case glslang::ElfR16:
552 case glslang::ElfR8:
553 case glslang::ElfRgba16Snorm:
554 case glslang::ElfRg16Snorm:
555 case glslang::ElfRg8Snorm:
556 case glslang::ElfR16Snorm:
557 case glslang::ElfR8Snorm:
558
559 case glslang::ElfRg32i:
560 case glslang::ElfRg16i:
561 case glslang::ElfRg8i:
562 case glslang::ElfR16i:
563 case glslang::ElfR8i:
564
565 case glslang::ElfRgb10a2ui:
566 case glslang::ElfRg32ui:
567 case glslang::ElfRg16ui:
568 case glslang::ElfRg8ui:
569 case glslang::ElfR16ui:
570 case glslang::ElfR8ui:
571 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
572 break;
573
574 default:
575 break;
576 }
577
578 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800579 switch (type.getQualifier().layoutFormat) {
580 case glslang::ElfNone: return spv::ImageFormatUnknown;
581 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
582 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
583 case glslang::ElfR32f: return spv::ImageFormatR32f;
584 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
585 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
586 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
587 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
588 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
589 case glslang::ElfR16f: return spv::ImageFormatR16f;
590 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
591 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
592 case glslang::ElfRg16: return spv::ImageFormatRg16;
593 case glslang::ElfRg8: return spv::ImageFormatRg8;
594 case glslang::ElfR16: return spv::ImageFormatR16;
595 case glslang::ElfR8: return spv::ImageFormatR8;
596 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
597 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
598 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
599 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
600 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
601 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
602 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
603 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
604 case glslang::ElfR32i: return spv::ImageFormatR32i;
605 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
606 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
607 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
608 case glslang::ElfR16i: return spv::ImageFormatR16i;
609 case glslang::ElfR8i: return spv::ImageFormatR8i;
610 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
611 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
612 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
613 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
614 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
615 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
616 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
617 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
618 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
619 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600620 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800621 }
622}
623
qining25262b32016-05-06 17:25:16 -0400624// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700625// descriptor set.
626bool IsDescriptorResource(const glslang::TType& type)
627{
John Kessenichf7497e22016-03-08 21:36:22 -0700628 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700629 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700630 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700631
632 // non block...
633 // basically samplerXXX/subpass/sampler/texture are all included
634 // if they are the global-scope-class, not the function parameter
635 // (or local, if they ever exist) class.
636 if (type.getBasicType() == glslang::EbtSampler)
637 return type.getQualifier().isUniformOrBuffer();
638
639 // None of the above.
640 return false;
641}
642
John Kesseniche0b6cad2015-12-24 10:30:13 -0700643void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
644{
645 if (child.layoutMatrix == glslang::ElmNone)
646 child.layoutMatrix = parent.layoutMatrix;
647
648 if (parent.invariant)
649 child.invariant = true;
650 if (parent.nopersp)
651 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800652#ifdef AMD_EXTENSIONS
653 if (parent.explicitInterp)
654 child.explicitInterp = true;
655#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700656 if (parent.flat)
657 child.flat = true;
658 if (parent.centroid)
659 child.centroid = true;
660 if (parent.patch)
661 child.patch = true;
662 if (parent.sample)
663 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800664 if (parent.coherent)
665 child.coherent = true;
666 if (parent.volatil)
667 child.volatil = true;
668 if (parent.restrict)
669 child.restrict = true;
670 if (parent.readonly)
671 child.readonly = true;
672 if (parent.writeonly)
673 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700674}
675
676bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
677{
John Kessenich7b9fa252016-01-21 18:56:57 -0700678 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700679 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600680 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700681 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600682 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700683}
684
John Kessenich140f3df2015-06-26 16:58:36 -0600685//
686// Implement the TGlslangToSpvTraverser class.
687//
688
Lei Zhang17535f72016-05-04 15:55:59 -0400689TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
690 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
691 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600692 inMain(false), mainTerminated(false), linkageOnly(false),
693 glslangIntermediate(glslangIntermediate)
694{
695 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
696
697 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700698 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600699 stdBuiltins = builder.import("GLSL.std.450");
700 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700701 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
702 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600703
704 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600705 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
706 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600707 builder.addSourceExtension(it->c_str());
708
709 // Add the top-level modes for this shader.
710
John Kessenich92187592016-02-01 13:45:25 -0700711 if (glslangIntermediate->getXfbMode()) {
712 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600713 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700714 }
John Kessenich140f3df2015-06-26 16:58:36 -0600715
716 unsigned int mode;
717 switch (glslangIntermediate->getStage()) {
718 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600719 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600720 break;
721
722 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600723 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600724 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
725 break;
726
727 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600728 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600729 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700730 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
731 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
732 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600733 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600734 }
John Kessenich4016e382016-07-15 11:53:56 -0600735 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600736 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
737
John Kesseniche6903322015-10-13 16:29:02 -0600738 switch (glslangIntermediate->getVertexSpacing()) {
739 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
740 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
741 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600742 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600743 }
John Kessenich4016e382016-07-15 11:53:56 -0600744 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600745 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
746
747 switch (glslangIntermediate->getVertexOrder()) {
748 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
749 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600750 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600751 }
John Kessenich4016e382016-07-15 11:53:56 -0600752 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600753 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
754
755 if (glslangIntermediate->getPointMode())
756 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600757 break;
758
759 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600760 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600761 switch (glslangIntermediate->getInputPrimitive()) {
762 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
763 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
764 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700765 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600766 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600767 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600768 }
John Kessenich4016e382016-07-15 11:53:56 -0600769 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600770 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600771
John Kessenich140f3df2015-06-26 16:58:36 -0600772 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
773
774 switch (glslangIntermediate->getOutputPrimitive()) {
775 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
776 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
777 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600778 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600779 }
John Kessenich4016e382016-07-15 11:53:56 -0600780 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600781 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
782 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
783 break;
784
785 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600786 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600787 if (glslangIntermediate->getPixelCenterInteger())
788 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600789
John Kessenich140f3df2015-06-26 16:58:36 -0600790 if (glslangIntermediate->getOriginUpperLeft())
791 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600792 else
793 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600794
795 if (glslangIntermediate->getEarlyFragmentTests())
796 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
797
798 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600799 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
800 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600801 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600802 }
John Kessenich4016e382016-07-15 11:53:56 -0600803 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600804 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
805
806 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
807 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600808 break;
809
810 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600811 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600812 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
813 glslangIntermediate->getLocalSize(1),
814 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600815 break;
816
817 default:
818 break;
819 }
820
821}
822
John Kessenich7ba63412015-12-20 17:37:07 -0700823// Finish everything and dump
824void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
825{
826 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100827 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
828 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700829
qiningda397332016-03-09 19:54:03 -0500830 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700831 builder.dump(out);
832}
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
835{
836 if (! mainTerminated) {
837 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
838 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600839 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600840 }
841}
842
843//
844// Implement the traversal functions.
845//
846// Return true from interior nodes to have the external traversal
847// continue on to children. Return false if children were
848// already processed.
849//
850
851//
qining25262b32016-05-06 17:25:16 -0400852// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600853// - uniform/input reads
854// - output writes
855// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
856// - something simple that degenerates into the last bullet
857//
858void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
859{
qining75d1d802016-04-06 14:42:01 -0400860 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
861 if (symbol->getType().getQualifier().isSpecConstant())
862 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
863
John Kessenich140f3df2015-06-26 16:58:36 -0600864 // getSymbolId() will set up all the IO decorations on the first call.
865 // Formal function parameters were mapped during makeFunctions().
866 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700867
868 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
869 if (builder.isPointer(id)) {
870 spv::StorageClass sc = builder.getStorageClass(id);
871 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
872 iOSet.insert(id);
873 }
874
875 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700876 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600877 // Prepare to generate code for the access
878
879 // L-value chains will be computed left to right. We're on the symbol now,
880 // which is the left-most part of the access chain, so now is "clear" time,
881 // followed by setting the base.
882 builder.clearAccessChain();
883
884 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700885 // except for
886 // A) "const in" arguments to a function, which are an intermediate object.
887 // See comments in handleUserFunctionCall().
888 // B) Specialization constants (normal constant don't even come in as a variable),
889 // These are also pure R-values.
890 glslang::TQualifier qualifier = symbol->getQualifier();
891 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
892 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600893 builder.setAccessChainRValue(id);
894 else
895 builder.setAccessChainLValue(id);
896 }
897}
898
899bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
900{
qining40887662016-04-03 22:20:42 -0400901 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
902 if (node->getType().getQualifier().isSpecConstant())
903 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
904
John Kessenich140f3df2015-06-26 16:58:36 -0600905 // First, handle special cases
906 switch (node->getOp()) {
907 case glslang::EOpAssign:
908 case glslang::EOpAddAssign:
909 case glslang::EOpSubAssign:
910 case glslang::EOpMulAssign:
911 case glslang::EOpVectorTimesMatrixAssign:
912 case glslang::EOpVectorTimesScalarAssign:
913 case glslang::EOpMatrixTimesScalarAssign:
914 case glslang::EOpMatrixTimesMatrixAssign:
915 case glslang::EOpDivAssign:
916 case glslang::EOpModAssign:
917 case glslang::EOpAndAssign:
918 case glslang::EOpInclusiveOrAssign:
919 case glslang::EOpExclusiveOrAssign:
920 case glslang::EOpLeftShiftAssign:
921 case glslang::EOpRightShiftAssign:
922 // A bin-op assign "a += b" means the same thing as "a = a + b"
923 // where a is evaluated before b. For a simple assignment, GLSL
924 // says to evaluate the left before the right. So, always, left
925 // node then right node.
926 {
927 // get the left l-value, save it away
928 builder.clearAccessChain();
929 node->getLeft()->traverse(this);
930 spv::Builder::AccessChain lValue = builder.getAccessChain();
931
932 // evaluate the right
933 builder.clearAccessChain();
934 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700935 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600936
937 if (node->getOp() != glslang::EOpAssign) {
938 // the left is also an r-value
939 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700940 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600941
942 // do the operation
qining25262b32016-05-06 17:25:16 -0400943 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
944 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600945 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
946 node->getType().getBasicType());
947
948 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700949 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600950 }
951
952 // store the result
953 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800954 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // assignments are expressions having an rValue after they are evaluated...
957 builder.clearAccessChain();
958 builder.setAccessChainRValue(rValue);
959 }
960 return false;
961 case glslang::EOpIndexDirect:
962 case glslang::EOpIndexDirectStruct:
963 {
964 // Get the left part of the access chain.
965 node->getLeft()->traverse(this);
966
967 // Add the next element in the chain
968
David Netoa901ffe2016-06-08 14:11:40 +0100969 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600970 if (! node->getLeft()->getType().isArray() &&
971 node->getLeft()->getType().isVector() &&
972 node->getOp() == glslang::EOpIndexDirect) {
973 // This is essentially a hard-coded vector swizzle of size 1,
974 // so short circuit the access-chain stuff with a swizzle.
975 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100976 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600977 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600978 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100979 int spvIndex = glslangIndex;
980 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
981 node->getOp() == glslang::EOpIndexDirectStruct)
982 {
983 // This may be, e.g., an anonymous block-member selection, which generally need
984 // index remapping due to hidden members in anonymous blocks.
985 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
986 assert(remapper.size() > 0);
987 spvIndex = remapper[glslangIndex];
988 }
John Kessenichebb50532016-05-16 19:22:05 -0600989
David Netoa901ffe2016-06-08 14:11:40 +0100990 // normal case for indexing array or structure or block
991 builder.accessChainPush(builder.makeIntConstant(spvIndex));
992
993 // Add capabilities here for accessing PointSize and clip/cull distance.
994 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600995 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100996 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600997 }
998 }
999 return false;
1000 case glslang::EOpIndexIndirect:
1001 {
1002 // Structure or array or vector indirection.
1003 // Will use native SPIR-V access-chain for struct and array indirection;
1004 // matrices are arrays of vectors, so will also work for a matrix.
1005 // Will use the access chain's 'component' for variable index into a vector.
1006
1007 // This adapter is building access chains left to right.
1008 // Set up the access chain to the left.
1009 node->getLeft()->traverse(this);
1010
1011 // save it so that computing the right side doesn't trash it
1012 spv::Builder::AccessChain partial = builder.getAccessChain();
1013
1014 // compute the next index in the chain
1015 builder.clearAccessChain();
1016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001017 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001018
1019 // restore the saved access chain
1020 builder.setAccessChain(partial);
1021
1022 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001023 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001024 else
John Kessenichfa668da2015-09-13 14:46:30 -06001025 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001026 }
1027 return false;
1028 case glslang::EOpVectorSwizzle:
1029 {
1030 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001031 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001032 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001033 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001034 }
1035 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001036 case glslang::EOpLogicalOr:
1037 case glslang::EOpLogicalAnd:
1038 {
1039
1040 // These may require short circuiting, but can sometimes be done as straight
1041 // binary operations. The right operand must be short circuited if it has
1042 // side effects, and should probably be if it is complex.
1043 if (isTrivial(node->getRight()->getAsTyped()))
1044 break; // handle below as a normal binary operation
1045 // otherwise, we need to do dynamic short circuiting on the right operand
1046 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1047 builder.clearAccessChain();
1048 builder.setAccessChainRValue(result);
1049 }
1050 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001051 default:
1052 break;
1053 }
1054
1055 // Assume generic binary op...
1056
John Kessenich32cfd492016-02-02 12:37:46 -07001057 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001058 builder.clearAccessChain();
1059 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001060 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001061
John Kessenich32cfd492016-02-02 12:37:46 -07001062 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001063 builder.clearAccessChain();
1064 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001065 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001066
John Kessenich32cfd492016-02-02 12:37:46 -07001067 // get result
1068 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001069 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001070 convertGlslangToSpvType(node->getType()), left, right,
1071 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001072
John Kessenich50e57562015-12-21 21:21:11 -07001073 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001074 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001075 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001076 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001077 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001078 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001079 return false;
1080 }
John Kessenich140f3df2015-06-26 16:58:36 -06001081}
1082
1083bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1084{
qining40887662016-04-03 22:20:42 -04001085 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1086 if (node->getType().getQualifier().isSpecConstant())
1087 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1088
John Kessenichfc51d282015-08-19 13:34:18 -06001089 spv::Id result = spv::NoResult;
1090
1091 // try texturing first
1092 result = createImageTextureFunctionCall(node);
1093 if (result != spv::NoResult) {
1094 builder.clearAccessChain();
1095 builder.setAccessChainRValue(result);
1096
1097 return false; // done with this node
1098 }
1099
1100 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001101
1102 if (node->getOp() == glslang::EOpArrayLength) {
1103 // Quite special; won't want to evaluate the operand.
1104
1105 // Normal .length() would have been constant folded by the front-end.
1106 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001107 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001108 assert(node->getOperand()->getType().isRuntimeSizedArray());
1109 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1110 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001111 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1112 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001113
1114 builder.clearAccessChain();
1115 builder.setAccessChainRValue(length);
1116
1117 return false;
1118 }
1119
John Kessenichfc51d282015-08-19 13:34:18 -06001120 // Start by evaluating the operand
1121
John Kessenich8c8505c2016-07-26 12:50:38 -06001122 // Does it need a swizzle inversion? If so, evaluation is inverted;
1123 // operate first on the swizzle base, then apply the swizzle.
1124 spv::Id invertedType = spv::NoType;
1125 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1126 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1127 invertedType = getInvertedSwizzleType(*node->getOperand());
1128
John Kessenich140f3df2015-06-26 16:58:36 -06001129 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001130 if (invertedType != spv::NoType)
1131 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1132 else
1133 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001134
Rex Xufc618912015-09-09 16:42:49 +08001135 spv::Id operand = spv::NoResult;
1136
1137 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1138 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001139 node->getOp() == glslang::EOpAtomicCounter ||
1140 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001141 operand = builder.accessChainGetLValue(); // Special case l-value operands
1142 else
John Kessenich32cfd492016-02-02 12:37:46 -07001143 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001146 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001147
1148 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001149 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001150 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001151
1152 // if not, then possibly an operation
1153 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001154 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001157 if (invertedType)
1158 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1159
John Kessenich140f3df2015-06-26 16:58:36 -06001160 builder.clearAccessChain();
1161 builder.setAccessChainRValue(result);
1162
1163 return false; // done with this node
1164 }
1165
1166 // it must be a special case, check...
1167 switch (node->getOp()) {
1168 case glslang::EOpPostIncrement:
1169 case glslang::EOpPostDecrement:
1170 case glslang::EOpPreIncrement:
1171 case glslang::EOpPreDecrement:
1172 {
1173 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001174 spv::Id one = 0;
1175 if (node->getBasicType() == glslang::EbtFloat)
1176 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001177 else if (node->getBasicType() == glslang::EbtDouble)
1178 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001179 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1180 one = builder.makeInt64Constant(1);
1181 else
1182 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001183 glslang::TOperator op;
1184 if (node->getOp() == glslang::EOpPreIncrement ||
1185 node->getOp() == glslang::EOpPostIncrement)
1186 op = glslang::EOpAdd;
1187 else
1188 op = glslang::EOpSub;
1189
qining25262b32016-05-06 17:25:16 -04001190 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1191 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001192 convertGlslangToSpvType(node->getType()), operand, one,
1193 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001194 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001195
1196 // The result of operation is always stored, but conditionally the
1197 // consumed result. The consumed result is always an r-value.
1198 builder.accessChainStore(result);
1199 builder.clearAccessChain();
1200 if (node->getOp() == glslang::EOpPreIncrement ||
1201 node->getOp() == glslang::EOpPreDecrement)
1202 builder.setAccessChainRValue(result);
1203 else
1204 builder.setAccessChainRValue(operand);
1205 }
1206
1207 return false;
1208
1209 case glslang::EOpEmitStreamVertex:
1210 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1211 return false;
1212 case glslang::EOpEndStreamPrimitive:
1213 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1214 return false;
1215
1216 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001217 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001218 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001219 }
John Kessenich140f3df2015-06-26 16:58:36 -06001220}
1221
1222bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1223{
qining27e04a02016-04-14 16:40:20 -04001224 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1225 if (node->getType().getQualifier().isSpecConstant())
1226 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1227
John Kessenichfc51d282015-08-19 13:34:18 -06001228 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001229 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1230 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001231
1232 // try texturing
1233 result = createImageTextureFunctionCall(node);
1234 if (result != spv::NoResult) {
1235 builder.clearAccessChain();
1236 builder.setAccessChainRValue(result);
1237
1238 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001239 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001240 // "imageStore" is a special case, which has no result
1241 return false;
1242 }
John Kessenichfc51d282015-08-19 13:34:18 -06001243
John Kessenich140f3df2015-06-26 16:58:36 -06001244 glslang::TOperator binOp = glslang::EOpNull;
1245 bool reduceComparison = true;
1246 bool isMatrix = false;
1247 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001248 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001249
1250 assert(node->getOp());
1251
1252 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1253
1254 switch (node->getOp()) {
1255 case glslang::EOpSequence:
1256 {
1257 if (preVisit)
1258 ++sequenceDepth;
1259 else
1260 --sequenceDepth;
1261
1262 if (sequenceDepth == 1) {
1263 // If this is the parent node of all the functions, we want to see them
1264 // early, so all call points have actual SPIR-V functions to reference.
1265 // In all cases, still let the traverser visit the children for us.
1266 makeFunctions(node->getAsAggregate()->getSequence());
1267
1268 // Also, we want all globals initializers to go into the entry of main(), before
1269 // anything else gets there, so visit out of order, doing them all now.
1270 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1271
1272 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1273 // so do them manually.
1274 visitFunctions(node->getAsAggregate()->getSequence());
1275
1276 return false;
1277 }
1278
1279 return true;
1280 }
1281 case glslang::EOpLinkerObjects:
1282 {
1283 if (visit == glslang::EvPreVisit)
1284 linkageOnly = true;
1285 else
1286 linkageOnly = false;
1287
1288 return true;
1289 }
1290 case glslang::EOpComma:
1291 {
1292 // processing from left to right naturally leaves the right-most
1293 // lying around in the access chain
1294 glslang::TIntermSequence& glslangOperands = node->getSequence();
1295 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1296 glslangOperands[i]->traverse(this);
1297
1298 return false;
1299 }
1300 case glslang::EOpFunction:
1301 if (visit == glslang::EvPreVisit) {
1302 if (isShaderEntrypoint(node)) {
1303 inMain = true;
1304 builder.setBuildPoint(shaderEntry->getLastBlock());
1305 } else {
1306 handleFunctionEntry(node);
1307 }
1308 } else {
1309 if (inMain)
1310 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001311 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001312 inMain = false;
1313 }
1314
1315 return true;
1316 case glslang::EOpParameters:
1317 // Parameters will have been consumed by EOpFunction processing, but not
1318 // the body, so we still visited the function node's children, making this
1319 // child redundant.
1320 return false;
1321 case glslang::EOpFunctionCall:
1322 {
1323 if (node->isUserDefined())
1324 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001325 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1326 if (result) {
1327 builder.clearAccessChain();
1328 builder.setAccessChainRValue(result);
1329 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001330 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001331
1332 return false;
1333 }
1334 case glslang::EOpConstructMat2x2:
1335 case glslang::EOpConstructMat2x3:
1336 case glslang::EOpConstructMat2x4:
1337 case glslang::EOpConstructMat3x2:
1338 case glslang::EOpConstructMat3x3:
1339 case glslang::EOpConstructMat3x4:
1340 case glslang::EOpConstructMat4x2:
1341 case glslang::EOpConstructMat4x3:
1342 case glslang::EOpConstructMat4x4:
1343 case glslang::EOpConstructDMat2x2:
1344 case glslang::EOpConstructDMat2x3:
1345 case glslang::EOpConstructDMat2x4:
1346 case glslang::EOpConstructDMat3x2:
1347 case glslang::EOpConstructDMat3x3:
1348 case glslang::EOpConstructDMat3x4:
1349 case glslang::EOpConstructDMat4x2:
1350 case glslang::EOpConstructDMat4x3:
1351 case glslang::EOpConstructDMat4x4:
1352 isMatrix = true;
1353 // fall through
1354 case glslang::EOpConstructFloat:
1355 case glslang::EOpConstructVec2:
1356 case glslang::EOpConstructVec3:
1357 case glslang::EOpConstructVec4:
1358 case glslang::EOpConstructDouble:
1359 case glslang::EOpConstructDVec2:
1360 case glslang::EOpConstructDVec3:
1361 case glslang::EOpConstructDVec4:
1362 case glslang::EOpConstructBool:
1363 case glslang::EOpConstructBVec2:
1364 case glslang::EOpConstructBVec3:
1365 case glslang::EOpConstructBVec4:
1366 case glslang::EOpConstructInt:
1367 case glslang::EOpConstructIVec2:
1368 case glslang::EOpConstructIVec3:
1369 case glslang::EOpConstructIVec4:
1370 case glslang::EOpConstructUint:
1371 case glslang::EOpConstructUVec2:
1372 case glslang::EOpConstructUVec3:
1373 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001374 case glslang::EOpConstructInt64:
1375 case glslang::EOpConstructI64Vec2:
1376 case glslang::EOpConstructI64Vec3:
1377 case glslang::EOpConstructI64Vec4:
1378 case glslang::EOpConstructUint64:
1379 case glslang::EOpConstructU64Vec2:
1380 case glslang::EOpConstructU64Vec3:
1381 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001382 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001383 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001384 {
1385 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001386 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001387 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001388 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001389 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001390 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001391 std::vector<spv::Id> constituents;
1392 for (int c = 0; c < (int)arguments.size(); ++c)
1393 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001394 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001395 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001396 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001397 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001398 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001399
1400 builder.clearAccessChain();
1401 builder.setAccessChainRValue(constructed);
1402
1403 return false;
1404 }
1405
1406 // These six are component-wise compares with component-wise results.
1407 // Forward on to createBinaryOperation(), requesting a vector result.
1408 case glslang::EOpLessThan:
1409 case glslang::EOpGreaterThan:
1410 case glslang::EOpLessThanEqual:
1411 case glslang::EOpGreaterThanEqual:
1412 case glslang::EOpVectorEqual:
1413 case glslang::EOpVectorNotEqual:
1414 {
1415 // Map the operation to a binary
1416 binOp = node->getOp();
1417 reduceComparison = false;
1418 switch (node->getOp()) {
1419 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1420 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1421 default: binOp = node->getOp(); break;
1422 }
1423
1424 break;
1425 }
1426 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001427 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001428 binOp = glslang::EOpMul;
1429 break;
1430 case glslang::EOpOuterProduct:
1431 // two vectors multiplied to make a matrix
1432 binOp = glslang::EOpOuterProduct;
1433 break;
1434 case glslang::EOpDot:
1435 {
qining25262b32016-05-06 17:25:16 -04001436 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001437 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001438 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001439 binOp = glslang::EOpMul;
1440 break;
1441 }
1442 case glslang::EOpMod:
1443 // when an aggregate, this is the floating-point mod built-in function,
1444 // which can be emitted by the one in createBinaryOperation()
1445 binOp = glslang::EOpMod;
1446 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001447 case glslang::EOpEmitVertex:
1448 case glslang::EOpEndPrimitive:
1449 case glslang::EOpBarrier:
1450 case glslang::EOpMemoryBarrier:
1451 case glslang::EOpMemoryBarrierAtomicCounter:
1452 case glslang::EOpMemoryBarrierBuffer:
1453 case glslang::EOpMemoryBarrierImage:
1454 case glslang::EOpMemoryBarrierShared:
1455 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001456 case glslang::EOpAllMemoryBarrierWithGroupSync:
1457 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1458 case glslang::EOpWorkgroupMemoryBarrier:
1459 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001460 noReturnValue = true;
1461 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1462 break;
1463
John Kessenich426394d2015-07-23 10:22:48 -06001464 case glslang::EOpAtomicAdd:
1465 case glslang::EOpAtomicMin:
1466 case glslang::EOpAtomicMax:
1467 case glslang::EOpAtomicAnd:
1468 case glslang::EOpAtomicOr:
1469 case glslang::EOpAtomicXor:
1470 case glslang::EOpAtomicExchange:
1471 case glslang::EOpAtomicCompSwap:
1472 atomic = true;
1473 break;
1474
John Kessenich140f3df2015-06-26 16:58:36 -06001475 default:
1476 break;
1477 }
1478
1479 //
1480 // See if it maps to a regular operation.
1481 //
John Kessenich140f3df2015-06-26 16:58:36 -06001482 if (binOp != glslang::EOpNull) {
1483 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1484 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1485 assert(left && right);
1486
1487 builder.clearAccessChain();
1488 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001489 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001490
1491 builder.clearAccessChain();
1492 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001493 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001494
qining25262b32016-05-06 17:25:16 -04001495 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001496 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001497 left->getType().getBasicType(), reduceComparison);
1498
1499 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001500 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001501 builder.clearAccessChain();
1502 builder.setAccessChainRValue(result);
1503
1504 return false;
1505 }
1506
John Kessenich426394d2015-07-23 10:22:48 -06001507 //
1508 // Create the list of operands.
1509 //
John Kessenich140f3df2015-06-26 16:58:36 -06001510 glslang::TIntermSequence& glslangOperands = node->getSequence();
1511 std::vector<spv::Id> operands;
1512 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001513 // special case l-value operands; there are just a few
1514 bool lvalue = false;
1515 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001516 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001517 case glslang::EOpModf:
1518 if (arg == 1)
1519 lvalue = true;
1520 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001521 case glslang::EOpInterpolateAtSample:
1522 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001523#ifdef AMD_EXTENSIONS
1524 case glslang::EOpInterpolateAtVertex:
1525#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001526 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001527 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001528
1529 // Does it need a swizzle inversion? If so, evaluation is inverted;
1530 // operate first on the swizzle base, then apply the swizzle.
1531 if (glslangOperands[0]->getAsOperator() &&
1532 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1533 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1534 }
Rex Xu7a26c172015-12-08 17:12:09 +08001535 break;
Rex Xud4782c12015-09-06 16:30:11 +08001536 case glslang::EOpAtomicAdd:
1537 case glslang::EOpAtomicMin:
1538 case glslang::EOpAtomicMax:
1539 case glslang::EOpAtomicAnd:
1540 case glslang::EOpAtomicOr:
1541 case glslang::EOpAtomicXor:
1542 case glslang::EOpAtomicExchange:
1543 case glslang::EOpAtomicCompSwap:
1544 if (arg == 0)
1545 lvalue = true;
1546 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001547 case glslang::EOpAddCarry:
1548 case glslang::EOpSubBorrow:
1549 if (arg == 2)
1550 lvalue = true;
1551 break;
1552 case glslang::EOpUMulExtended:
1553 case glslang::EOpIMulExtended:
1554 if (arg >= 2)
1555 lvalue = true;
1556 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001557 default:
1558 break;
1559 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001560 builder.clearAccessChain();
1561 if (invertedType != spv::NoType && arg == 0)
1562 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1563 else
1564 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001565 if (lvalue)
1566 operands.push_back(builder.accessChainGetLValue());
1567 else
John Kessenich32cfd492016-02-02 12:37:46 -07001568 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001569 }
John Kessenich426394d2015-07-23 10:22:48 -06001570
1571 if (atomic) {
1572 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001573 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001574 } else {
1575 // Pass through to generic operations.
1576 switch (glslangOperands.size()) {
1577 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001578 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001579 break;
1580 case 1:
qining25262b32016-05-06 17:25:16 -04001581 result = createUnaryOperation(
1582 node->getOp(), precision,
1583 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001584 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001585 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001586 break;
1587 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001588 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001589 break;
1590 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001591 if (invertedType)
1592 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001593 }
1594
1595 if (noReturnValue)
1596 return false;
1597
1598 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001599 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001600 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001601 } else {
1602 builder.clearAccessChain();
1603 builder.setAccessChainRValue(result);
1604 return false;
1605 }
1606}
1607
1608bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1609{
1610 // This path handles both if-then-else and ?:
1611 // The if-then-else has a node type of void, while
1612 // ?: has a non-void node type
1613 spv::Id result = 0;
1614 if (node->getBasicType() != glslang::EbtVoid) {
1615 // don't handle this as just on-the-fly temporaries, because there will be two names
1616 // and better to leave SSA to later passes
1617 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1618 }
1619
1620 // emit the condition before doing anything with selection
1621 node->getCondition()->traverse(this);
1622
1623 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001624 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001625
1626 if (node->getTrueBlock()) {
1627 // emit the "then" statement
1628 node->getTrueBlock()->traverse(this);
1629 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001630 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001631 }
1632
1633 if (node->getFalseBlock()) {
1634 ifBuilder.makeBeginElse();
1635 // emit the "else" statement
1636 node->getFalseBlock()->traverse(this);
1637 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001638 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001639 }
1640
1641 ifBuilder.makeEndIf();
1642
1643 if (result) {
1644 // GLSL only has r-values as the result of a :?, but
1645 // if we have an l-value, that can be more efficient if it will
1646 // become the base of a complex r-value expression, because the
1647 // next layer copies r-values into memory to use the access-chain mechanism
1648 builder.clearAccessChain();
1649 builder.setAccessChainLValue(result);
1650 }
1651
1652 return false;
1653}
1654
1655bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1656{
1657 // emit and get the condition before doing anything with switch
1658 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001659 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001660
1661 // browse the children to sort out code segments
1662 int defaultSegment = -1;
1663 std::vector<TIntermNode*> codeSegments;
1664 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1665 std::vector<int> caseValues;
1666 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1667 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1668 TIntermNode* child = *c;
1669 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001670 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001671 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001672 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001673 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1674 } else
1675 codeSegments.push_back(child);
1676 }
1677
qining25262b32016-05-06 17:25:16 -04001678 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001679 // statements between the last case and the end of the switch statement
1680 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1681 (int)codeSegments.size() == defaultSegment)
1682 codeSegments.push_back(nullptr);
1683
1684 // make the switch statement
1685 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001686 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001687
1688 // emit all the code in the segments
1689 breakForLoop.push(false);
1690 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1691 builder.nextSwitchSegment(segmentBlocks, s);
1692 if (codeSegments[s])
1693 codeSegments[s]->traverse(this);
1694 else
1695 builder.addSwitchBreak();
1696 }
1697 breakForLoop.pop();
1698
1699 builder.endSwitch(segmentBlocks);
1700
1701 return false;
1702}
1703
1704void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1705{
1706 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001707 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001708
1709 builder.clearAccessChain();
1710 builder.setAccessChainRValue(constant);
1711}
1712
1713bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1714{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001715 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001716 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001717 // Spec requires back edges to target header blocks, and every header block
1718 // must dominate its merge block. Make a header block first to ensure these
1719 // conditions are met. By definition, it will contain OpLoopMerge, followed
1720 // by a block-ending branch. But we don't want to put any other body/test
1721 // instructions in it, since the body/test may have arbitrary instructions,
1722 // including merges of its own.
1723 builder.setBuildPoint(&blocks.head);
1724 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001725 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001726 spv::Block& test = builder.makeNewBlock();
1727 builder.createBranch(&test);
1728
1729 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001730 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001731 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001732 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001733 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1734
1735 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001736 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001737 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001738 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001739 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001740 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001741
1742 builder.setBuildPoint(&blocks.continue_target);
1743 if (node->getTerminal())
1744 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001745 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001746 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001747 builder.createBranch(&blocks.body);
1748
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001749 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001750 builder.setBuildPoint(&blocks.body);
1751 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001752 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001753 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001754 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001755
1756 builder.setBuildPoint(&blocks.continue_target);
1757 if (node->getTerminal())
1758 node->getTerminal()->traverse(this);
1759 if (node->getTest()) {
1760 node->getTest()->traverse(this);
1761 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001762 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001763 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001764 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001765 // TODO: unless there was a break/return/discard instruction
1766 // somewhere in the body, this is an infinite loop, so we should
1767 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001768 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001769 }
John Kessenich140f3df2015-06-26 16:58:36 -06001770 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001771 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001772 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001773 return false;
1774}
1775
1776bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1777{
1778 if (node->getExpression())
1779 node->getExpression()->traverse(this);
1780
1781 switch (node->getFlowOp()) {
1782 case glslang::EOpKill:
1783 builder.makeDiscard();
1784 break;
1785 case glslang::EOpBreak:
1786 if (breakForLoop.top())
1787 builder.createLoopExit();
1788 else
1789 builder.addSwitchBreak();
1790 break;
1791 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001792 builder.createLoopContinue();
1793 break;
1794 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001795 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001796 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001797 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001798 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001799
1800 builder.clearAccessChain();
1801 break;
1802
1803 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001804 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001805 break;
1806 }
1807
1808 return false;
1809}
1810
1811spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1812{
qining25262b32016-05-06 17:25:16 -04001813 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001814 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001815 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001816 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001817 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001818 }
1819
1820 // Now, handle actual variables
1821 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1822 spv::Id spvType = convertGlslangToSpvType(node->getType());
1823
1824 const char* name = node->getName().c_str();
1825 if (glslang::IsAnonymous(name))
1826 name = "";
1827
1828 return builder.createVariable(storageClass, spvType, name);
1829}
1830
1831// Return type Id of the sampled type.
1832spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1833{
1834 switch (sampler.type) {
1835 case glslang::EbtFloat: return builder.makeFloatType(32);
1836 case glslang::EbtInt: return builder.makeIntType(32);
1837 case glslang::EbtUint: return builder.makeUintType(32);
1838 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001839 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001840 return builder.makeFloatType(32);
1841 }
1842}
1843
John Kessenich8c8505c2016-07-26 12:50:38 -06001844// If node is a swizzle operation, return the type that should be used if
1845// the swizzle base is first consumed by another operation, before the swizzle
1846// is applied.
1847spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1848{
1849 if (node.getAsOperator() &&
1850 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1851 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1852 else
1853 return spv::NoType;
1854}
1855
1856// When inverting a swizzle with a parent op, this function
1857// will apply the swizzle operation to a completed parent operation.
1858spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1859{
1860 std::vector<unsigned> swizzle;
1861 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1862 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1863}
1864
1865
1866// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1867void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1868{
1869 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1870 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1871 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1872}
1873
John Kessenich3ac051e2015-12-20 11:29:16 -07001874// Convert from a glslang type to an SPV type, by calling into a
1875// recursive version of this function. This establishes the inherited
1876// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001877spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1878{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001879 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001880}
1881
1882// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001883// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001884// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001885spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001886{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001887 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001888
1889 switch (type.getBasicType()) {
1890 case glslang::EbtVoid:
1891 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001892 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001893 break;
1894 case glslang::EbtFloat:
1895 spvType = builder.makeFloatType(32);
1896 break;
1897 case glslang::EbtDouble:
1898 spvType = builder.makeFloatType(64);
1899 break;
1900 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001901 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1902 // a 32-bit int where non-0 means true.
1903 if (explicitLayout != glslang::ElpNone)
1904 spvType = builder.makeUintType(32);
1905 else
1906 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001907 break;
1908 case glslang::EbtInt:
1909 spvType = builder.makeIntType(32);
1910 break;
1911 case glslang::EbtUint:
1912 spvType = builder.makeUintType(32);
1913 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001914 case glslang::EbtInt64:
1915 builder.addCapability(spv::CapabilityInt64);
1916 spvType = builder.makeIntType(64);
1917 break;
1918 case glslang::EbtUint64:
1919 builder.addCapability(spv::CapabilityInt64);
1920 spvType = builder.makeUintType(64);
1921 break;
John Kessenich426394d2015-07-23 10:22:48 -06001922 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001923 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001924 spvType = builder.makeUintType(32);
1925 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001926 case glslang::EbtSampler:
1927 {
1928 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001929 if (sampler.sampler) {
1930 // pure sampler
1931 spvType = builder.makeSamplerType();
1932 } else {
1933 // an image is present, make its type
1934 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1935 sampler.image ? 2 : 1, TranslateImageFormat(type));
1936 if (sampler.combined) {
1937 // already has both image and sampler, make the combined type
1938 spvType = builder.makeSampledImageType(spvType);
1939 }
John Kessenich55e7d112015-11-15 21:33:39 -07001940 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001941 }
John Kessenich140f3df2015-06-26 16:58:36 -06001942 break;
1943 case glslang::EbtStruct:
1944 case glslang::EbtBlock:
1945 {
1946 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001947 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001948
1949 // Try to share structs for different layouts, but not yet for other
1950 // kinds of qualification (primarily not yet including interpolant qualification).
1951 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001952 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001953 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001954 break;
1955
1956 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001957 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001958 memberRemapper[glslangMembers].resize(glslangMembers->size());
1959 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001960 }
1961 break;
1962 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001963 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001964 break;
1965 }
1966
1967 if (type.isMatrix())
1968 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1969 else {
1970 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1971 if (type.getVectorSize() > 1)
1972 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1973 }
1974
1975 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001976 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1977
John Kessenichc9a80832015-09-12 12:17:44 -06001978 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001979 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001980 // We need to decorate array strides for types needing explicit layout, except blocks.
1981 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001982 // Use a dummy glslang type for querying internal strides of
1983 // arrays of arrays, but using just a one-dimensional array.
1984 glslang::TType simpleArrayType(type, 0); // deference type of the array
1985 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1986 simpleArrayType.getArraySizes().dereference();
1987
1988 // Will compute the higher-order strides here, rather than making a whole
1989 // pile of types and doing repetitive recursion on their contents.
1990 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1991 }
John Kessenichf8842e52016-01-04 19:22:56 -07001992
1993 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001994 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001995 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001996 if (stride > 0)
1997 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001998 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001999 }
2000 } else {
2001 // single-dimensional array, and don't yet have stride
2002
John Kessenichf8842e52016-01-04 19:22:56 -07002003 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002004 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2005 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002006 }
John Kessenich31ed4832015-09-09 17:51:38 -06002007
John Kessenichc9a80832015-09-12 12:17:44 -06002008 // Do the outer dimension, which might not be known for a runtime-sized array
2009 if (type.isRuntimeSizedArray()) {
2010 spvType = builder.makeRuntimeArray(spvType);
2011 } else {
2012 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002013 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002014 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002015 if (stride > 0)
2016 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002017 }
2018
2019 return spvType;
2020}
2021
John Kessenich6090df02016-06-30 21:18:02 -06002022
2023// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2024// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2025// Mutually recursive with convertGlslangToSpvType().
2026spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2027 const glslang::TTypeList* glslangMembers,
2028 glslang::TLayoutPacking explicitLayout,
2029 const glslang::TQualifier& qualifier)
2030{
2031 // Create a vector of struct types for SPIR-V to consume
2032 std::vector<spv::Id> spvMembers;
2033 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2034 int locationOffset = 0; // for use across struct members, when they are called recursively
2035 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2036 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2037 if (glslangMember.hiddenMember()) {
2038 ++memberDelta;
2039 if (type.getBasicType() == glslang::EbtBlock)
2040 memberRemapper[glslangMembers][i] = -1;
2041 } else {
2042 if (type.getBasicType() == glslang::EbtBlock)
2043 memberRemapper[glslangMembers][i] = i - memberDelta;
2044 // modify just this child's view of the qualifier
2045 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2046 InheritQualifiers(memberQualifier, qualifier);
2047
2048 // manually inherit location; it's more complex
2049 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2050 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2051 if (qualifier.hasLocation())
2052 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2053
2054 // recurse
2055 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2056 }
2057 }
2058
2059 // Make the SPIR-V type
2060 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2061 if (! HasNonLayoutQualifiers(qualifier))
2062 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2063
2064 // Decorate it
2065 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2066
2067 return spvType;
2068}
2069
2070void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2071 const glslang::TTypeList* glslangMembers,
2072 glslang::TLayoutPacking explicitLayout,
2073 const glslang::TQualifier& qualifier,
2074 spv::Id spvType)
2075{
2076 // Name and decorate the non-hidden members
2077 int offset = -1;
2078 int locationOffset = 0; // for use within the members of this struct
2079 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2080 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2081 int member = i;
2082 if (type.getBasicType() == glslang::EbtBlock)
2083 member = memberRemapper[glslangMembers][i];
2084
2085 // modify just this child's view of the qualifier
2086 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2087 InheritQualifiers(memberQualifier, qualifier);
2088
2089 // using -1 above to indicate a hidden member
2090 if (member >= 0) {
2091 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2092 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2093 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2094 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2095 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2096 if (type.getBasicType() == glslang::EbtBlock) {
2097 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2098 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2099 }
2100 }
2101 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2102
2103 if (qualifier.storage == glslang::EvqBuffer) {
2104 std::vector<spv::Decoration> memory;
2105 TranslateMemoryDecoration(memberQualifier, memory);
2106 for (unsigned int i = 0; i < memory.size(); ++i)
2107 addMemberDecoration(spvType, member, memory[i]);
2108 }
2109
John Kessenich2f47bc92016-06-30 21:47:35 -06002110 // Compute location decoration; tricky based on whether inheritance is at play and
2111 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002112 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2113 // probably move to the linker stage of the front end proper, and just have the
2114 // answer sitting already distributed throughout the individual member locations.
2115 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002116 // Ignore member locations if the container is an array, as that's
2117 // ill-specified and decisions have been made to not allow this anyway.
2118 // The object itself must have a location, and that comes out from decorating the object,
2119 // not the type (this code decorates types).
2120 if (! type.isArray()) {
2121 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2122 // struct members should not have explicit locations
2123 assert(type.getBasicType() != glslang::EbtStruct);
2124 location = memberQualifier.layoutLocation;
2125 } else if (type.getBasicType() != glslang::EbtBlock) {
2126 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2127 // The members, and their nested types, must not themselves have Location decorations.
2128 } else if (qualifier.hasLocation()) // inheritance
2129 location = qualifier.layoutLocation + locationOffset;
2130 }
John Kessenich6090df02016-06-30 21:18:02 -06002131 if (location >= 0)
2132 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2133
John Kessenich2f47bc92016-06-30 21:47:35 -06002134 if (qualifier.hasLocation()) // track for upcoming inheritance
2135 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2136
John Kessenich6090df02016-06-30 21:18:02 -06002137 // component, XFB, others
2138 if (glslangMember.getQualifier().hasComponent())
2139 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2140 if (glslangMember.getQualifier().hasXfbOffset())
2141 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2142 else if (explicitLayout != glslang::ElpNone) {
2143 // figure out what to do with offset, which is accumulating
2144 int nextOffset;
2145 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2146 if (offset >= 0)
2147 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2148 offset = nextOffset;
2149 }
2150
2151 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2152 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2153
2154 // built-in variable decorations
2155 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002156 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002157 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2158 }
2159 }
2160
2161 // Decorate the structure
2162 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2163 addDecoration(spvType, TranslateBlockDecoration(type));
2164 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2165 builder.addCapability(spv::CapabilityGeometryStreams);
2166 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2167 }
2168 if (glslangIntermediate->getXfbMode()) {
2169 builder.addCapability(spv::CapabilityTransformFeedback);
2170 if (type.getQualifier().hasXfbStride())
2171 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2172 if (type.getQualifier().hasXfbBuffer())
2173 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2174 }
2175}
2176
John Kessenich6c292d32016-02-15 20:58:50 -07002177// Turn the expression forming the array size into an id.
2178// This is not quite trivial, because of specialization constants.
2179// Sometimes, a raw constant is turned into an Id, and sometimes
2180// a specialization constant expression is.
2181spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2182{
2183 // First, see if this is sized with a node, meaning a specialization constant:
2184 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2185 if (specNode != nullptr) {
2186 builder.clearAccessChain();
2187 specNode->traverse(this);
2188 return accessChainLoad(specNode->getAsTyped()->getType());
2189 }
qining25262b32016-05-06 17:25:16 -04002190
John Kessenich6c292d32016-02-15 20:58:50 -07002191 // Otherwise, need a compile-time (front end) size, get it:
2192 int size = arraySizes.getDimSize(dim);
2193 assert(size > 0);
2194 return builder.makeUintConstant(size);
2195}
2196
John Kessenich103bef92016-02-08 21:38:15 -07002197// Wrap the builder's accessChainLoad to:
2198// - localize handling of RelaxedPrecision
2199// - use the SPIR-V inferred type instead of another conversion of the glslang type
2200// (avoids unnecessary work and possible type punning for structures)
2201// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002202spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2203{
John Kessenich103bef92016-02-08 21:38:15 -07002204 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2205 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2206
2207 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002208 if (type.getBasicType() == glslang::EbtBool) {
2209 if (builder.isScalarType(nominalTypeId)) {
2210 // Conversion for bool
2211 spv::Id boolType = builder.makeBoolType();
2212 if (nominalTypeId != boolType)
2213 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2214 } else if (builder.isVectorType(nominalTypeId)) {
2215 // Conversion for bvec
2216 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2217 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2218 if (nominalTypeId != bvecType)
2219 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2220 }
2221 }
John Kessenich103bef92016-02-08 21:38:15 -07002222
2223 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002224}
2225
Rex Xu27253232016-02-23 17:51:09 +08002226// Wrap the builder's accessChainStore to:
2227// - do conversion of concrete to abstract type
2228void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2229{
2230 // Need to convert to abstract types when necessary
2231 if (type.getBasicType() == glslang::EbtBool) {
2232 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2233
2234 if (builder.isScalarType(nominalTypeId)) {
2235 // Conversion for bool
2236 spv::Id boolType = builder.makeBoolType();
2237 if (nominalTypeId != boolType) {
2238 spv::Id zero = builder.makeUintConstant(0);
2239 spv::Id one = builder.makeUintConstant(1);
2240 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2241 }
2242 } else if (builder.isVectorType(nominalTypeId)) {
2243 // Conversion for bvec
2244 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2245 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2246 if (nominalTypeId != bvecType) {
2247 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2248 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2249 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2250 }
2251 }
2252 }
2253
2254 builder.accessChainStore(rvalue);
2255}
2256
John Kessenichf85e8062015-12-19 13:57:10 -07002257// Decide whether or not this type should be
2258// decorated with offsets and strides, and if so
2259// whether std140 or std430 rules should be applied.
2260glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002261{
John Kessenichf85e8062015-12-19 13:57:10 -07002262 // has to be a block
2263 if (type.getBasicType() != glslang::EbtBlock)
2264 return glslang::ElpNone;
2265
2266 // has to be a uniform or buffer block
2267 if (type.getQualifier().storage != glslang::EvqUniform &&
2268 type.getQualifier().storage != glslang::EvqBuffer)
2269 return glslang::ElpNone;
2270
2271 // return the layout to use
2272 switch (type.getQualifier().layoutPacking) {
2273 case glslang::ElpStd140:
2274 case glslang::ElpStd430:
2275 return type.getQualifier().layoutPacking;
2276 default:
2277 return glslang::ElpNone;
2278 }
John Kessenich31ed4832015-09-09 17:51:38 -06002279}
2280
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002281// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002282int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002283{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002284 int size;
John Kessenich49987892015-12-29 17:11:44 -07002285 int stride;
2286 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002287
2288 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002289}
2290
John Kessenich49987892015-12-29 17:11:44 -07002291// 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 -07002292// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002293int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002294{
John Kessenich49987892015-12-29 17:11:44 -07002295 glslang::TType elementType;
2296 elementType.shallowCopy(matrixType);
2297 elementType.clearArraySizes();
2298
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002299 int size;
John Kessenich49987892015-12-29 17:11:44 -07002300 int stride;
2301 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2302
2303 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002304}
2305
John Kessenich5e4b1242015-08-06 22:53:06 -06002306// Given a member type of a struct, realign the current offset for it, and compute
2307// the next (not yet aligned) offset for the next member, which will get aligned
2308// on the next call.
2309// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2310// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2311// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002312void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002313 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002314{
2315 // this will get a positive value when deemed necessary
2316 nextOffset = -1;
2317
John Kessenich5e4b1242015-08-06 22:53:06 -06002318 // override anything in currentOffset with user-set offset
2319 if (memberType.getQualifier().hasOffset())
2320 currentOffset = memberType.getQualifier().layoutOffset;
2321
2322 // It could be that current linker usage in glslang updated all the layoutOffset,
2323 // in which case the following code does not matter. But, that's not quite right
2324 // once cross-compilation unit GLSL validation is done, as the original user
2325 // settings are needed in layoutOffset, and then the following will come into play.
2326
John Kessenichf85e8062015-12-19 13:57:10 -07002327 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002328 if (! memberType.getQualifier().hasOffset())
2329 currentOffset = -1;
2330
2331 return;
2332 }
2333
John Kessenichf85e8062015-12-19 13:57:10 -07002334 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 if (currentOffset < 0)
2336 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002337
John Kessenich5e4b1242015-08-06 22:53:06 -06002338 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2339 // but possibly not yet correctly aligned.
2340
2341 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002342 int dummyStride;
2343 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002344 glslang::RoundToPow2(currentOffset, memberAlignment);
2345 nextOffset = currentOffset + memberSize;
2346}
2347
David Netoa901ffe2016-06-08 14:11:40 +01002348void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002349{
David Netoa901ffe2016-06-08 14:11:40 +01002350 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2351 switch (glslangBuiltIn)
2352 {
2353 case glslang::EbvClipDistance:
2354 case glslang::EbvCullDistance:
2355 case glslang::EbvPointSize:
2356 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2357 // Alternately, we could just call this for any glslang built-in, since the
2358 // capability already guards against duplicates.
2359 TranslateBuiltInDecoration(glslangBuiltIn, false);
2360 break;
2361 default:
2362 // Capabilities were already generated when the struct was declared.
2363 break;
2364 }
John Kessenichebb50532016-05-16 19:22:05 -06002365}
2366
John Kessenich140f3df2015-06-26 16:58:36 -06002367bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2368{
John Kessenich4d65ee32016-03-12 18:17:47 -07002369 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002370 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002371 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002372}
2373
2374// Make all the functions, skeletally, without actually visiting their bodies.
2375void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2376{
2377 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2378 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2379 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2380 continue;
2381
2382 // We're on a user function. Set up the basic interface for the function now,
2383 // so that it's available to call.
2384 // Translating the body will happen later.
2385 //
qining25262b32016-05-06 17:25:16 -04002386 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002387 // function. What it is an address of varies:
2388 //
2389 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2390 // so that write needs to be to a copy, hence the address of a copy works.
2391 //
2392 // - "const in" parameters can just be the r-value, as no writes need occur.
2393 //
2394 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2395 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2396
2397 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002398 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002399 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2400
2401 for (int p = 0; p < (int)parameters.size(); ++p) {
2402 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2403 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002404 if (paramType.isOpaque())
2405 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2406 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002407 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2408 else
2409 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002410 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002411 paramTypes.push_back(typeId);
2412 }
2413
2414 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002415 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2416 convertGlslangToSpvType(glslFunction->getType()),
2417 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002418
2419 // Track function to emit/call later
2420 functionMap[glslFunction->getName().c_str()] = function;
2421
2422 // Set the parameter id's
2423 for (int p = 0; p < (int)parameters.size(); ++p) {
2424 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2425 // give a name too
2426 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2427 }
2428 }
2429}
2430
2431// Process all the initializers, while skipping the functions and link objects
2432void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2433{
2434 builder.setBuildPoint(shaderEntry->getLastBlock());
2435 for (int i = 0; i < (int)initializers.size(); ++i) {
2436 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2437 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2438
2439 // We're on a top-level node that's not a function. Treat as an initializer, whose
2440 // code goes into the beginning of main.
2441 initializer->traverse(this);
2442 }
2443 }
2444}
2445
2446// Process all the functions, while skipping initializers.
2447void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2448{
2449 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2450 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2451 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2452 node->traverse(this);
2453 }
2454}
2455
2456void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2457{
qining25262b32016-05-06 17:25:16 -04002458 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002459 // that called makeFunctions().
2460 spv::Function* function = functionMap[node->getName().c_str()];
2461 spv::Block* functionBlock = function->getEntryBlock();
2462 builder.setBuildPoint(functionBlock);
2463}
2464
Rex Xu04db3f52015-09-16 11:44:02 +08002465void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002466{
Rex Xufc618912015-09-09 16:42:49 +08002467 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002468
2469 glslang::TSampler sampler = {};
2470 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002471 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002472 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2473 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2474 }
2475
John Kessenich140f3df2015-06-26 16:58:36 -06002476 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2477 builder.clearAccessChain();
2478 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002479
2480 // Special case l-value operands
2481 bool lvalue = false;
2482 switch (node.getOp()) {
2483 case glslang::EOpImageAtomicAdd:
2484 case glslang::EOpImageAtomicMin:
2485 case glslang::EOpImageAtomicMax:
2486 case glslang::EOpImageAtomicAnd:
2487 case glslang::EOpImageAtomicOr:
2488 case glslang::EOpImageAtomicXor:
2489 case glslang::EOpImageAtomicExchange:
2490 case glslang::EOpImageAtomicCompSwap:
2491 if (i == 0)
2492 lvalue = true;
2493 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002494 case glslang::EOpSparseImageLoad:
2495 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2496 lvalue = true;
2497 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002498 case glslang::EOpSparseTexture:
2499 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2500 lvalue = true;
2501 break;
2502 case glslang::EOpSparseTextureClamp:
2503 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2504 lvalue = true;
2505 break;
2506 case glslang::EOpSparseTextureLod:
2507 case glslang::EOpSparseTextureOffset:
2508 if (i == 3)
2509 lvalue = true;
2510 break;
2511 case glslang::EOpSparseTextureFetch:
2512 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2513 lvalue = true;
2514 break;
2515 case glslang::EOpSparseTextureFetchOffset:
2516 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2517 lvalue = true;
2518 break;
2519 case glslang::EOpSparseTextureLodOffset:
2520 case glslang::EOpSparseTextureGrad:
2521 case glslang::EOpSparseTextureOffsetClamp:
2522 if (i == 4)
2523 lvalue = true;
2524 break;
2525 case glslang::EOpSparseTextureGradOffset:
2526 case glslang::EOpSparseTextureGradClamp:
2527 if (i == 5)
2528 lvalue = true;
2529 break;
2530 case glslang::EOpSparseTextureGradOffsetClamp:
2531 if (i == 6)
2532 lvalue = true;
2533 break;
2534 case glslang::EOpSparseTextureGather:
2535 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2536 lvalue = true;
2537 break;
2538 case glslang::EOpSparseTextureGatherOffset:
2539 case glslang::EOpSparseTextureGatherOffsets:
2540 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2541 lvalue = true;
2542 break;
Rex Xufc618912015-09-09 16:42:49 +08002543 default:
2544 break;
2545 }
2546
Rex Xu6b86d492015-09-16 17:48:22 +08002547 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002548 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002549 else
John Kessenich32cfd492016-02-02 12:37:46 -07002550 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002551 }
2552}
2553
John Kessenichfc51d282015-08-19 13:34:18 -06002554void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002555{
John Kessenichfc51d282015-08-19 13:34:18 -06002556 builder.clearAccessChain();
2557 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002558 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002559}
John Kessenich140f3df2015-06-26 16:58:36 -06002560
John Kessenichfc51d282015-08-19 13:34:18 -06002561spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2562{
Rex Xufc618912015-09-09 16:42:49 +08002563 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002564 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002565 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002566 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002567
John Kessenichfc51d282015-08-19 13:34:18 -06002568 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002569 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2570 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2571 std::vector<spv::Id> arguments;
2572 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002573 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002574 else
2575 translateArguments(*node->getAsUnaryNode(), arguments);
2576 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2577
2578 spv::Builder::TextureParameters params = { };
2579 params.sampler = arguments[0];
2580
Rex Xu04db3f52015-09-16 11:44:02 +08002581 glslang::TCrackedTextureOp cracked;
2582 node->crackTexture(sampler, cracked);
2583
John Kessenichfc51d282015-08-19 13:34:18 -06002584 // Check for queries
2585 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002586 // a sampled image needs to have the image extracted first
2587 if (builder.isSampledImage(params.sampler))
2588 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002589 switch (node->getOp()) {
2590 case glslang::EOpImageQuerySize:
2591 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002592 if (arguments.size() > 1) {
2593 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002594 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002595 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002596 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002597 case glslang::EOpImageQuerySamples:
2598 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002599 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002600 case glslang::EOpTextureQueryLod:
2601 params.coords = arguments[1];
2602 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2603 case glslang::EOpTextureQueryLevels:
2604 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002605 case glslang::EOpSparseTexelsResident:
2606 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002607 default:
2608 assert(0);
2609 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002610 }
John Kessenich140f3df2015-06-26 16:58:36 -06002611 }
2612
Rex Xufc618912015-09-09 16:42:49 +08002613 // Check for image functions other than queries
2614 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002615 std::vector<spv::Id> operands;
2616 auto opIt = arguments.begin();
2617 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002618
2619 // Handle subpass operations
2620 // TODO: GLSL should change to have the "MS" only on the type rather than the
2621 // built-in function.
2622 if (cracked.subpass) {
2623 // add on the (0,0) coordinate
2624 spv::Id zero = builder.makeIntConstant(0);
2625 std::vector<spv::Id> comps;
2626 comps.push_back(zero);
2627 comps.push_back(zero);
2628 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2629 if (sampler.ms) {
2630 operands.push_back(spv::ImageOperandsSampleMask);
2631 operands.push_back(*(opIt++));
2632 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002633 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002634 }
2635
John Kessenich56bab042015-09-16 10:54:31 -06002636 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002637 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002638 if (sampler.ms) {
2639 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002640 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002641 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002642 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2643 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002644 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002645 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002646 if (sampler.ms) {
2647 operands.push_back(*(opIt + 1));
2648 operands.push_back(spv::ImageOperandsSampleMask);
2649 operands.push_back(*opIt);
2650 } else
2651 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002652 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002653 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2654 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002655 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002656 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2657 builder.addCapability(spv::CapabilitySparseResidency);
2658 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2659 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2660
2661 if (sampler.ms) {
2662 operands.push_back(spv::ImageOperandsSampleMask);
2663 operands.push_back(*opIt++);
2664 }
2665
2666 // Create the return type that was a special structure
2667 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002668 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002669 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2670 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2671
2672 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2673
2674 // Decode the return type
2675 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2676 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002677 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002678 // Process image atomic operations
2679
2680 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2681 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002682 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002683
John Kessenich8c8505c2016-07-26 12:50:38 -06002684 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002685 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002686
2687 std::vector<spv::Id> operands;
2688 operands.push_back(pointer);
2689 for (; opIt != arguments.end(); ++opIt)
2690 operands.push_back(*opIt);
2691
John Kessenich8c8505c2016-07-26 12:50:38 -06002692 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002693 }
2694 }
2695
2696 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002697 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002698 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2699
John Kessenichfc51d282015-08-19 13:34:18 -06002700 // check for bias argument
2701 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002702 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002703 int nonBiasArgCount = 2;
2704 if (cracked.offset)
2705 ++nonBiasArgCount;
2706 if (cracked.grad)
2707 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002708 if (cracked.lodClamp)
2709 ++nonBiasArgCount;
2710 if (sparse)
2711 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002712
2713 if ((int)arguments.size() > nonBiasArgCount)
2714 bias = true;
2715 }
2716
John Kessenicha5c33d62016-06-02 23:45:21 -06002717 // See if the sampler param should really be just the SPV image part
2718 if (cracked.fetch) {
2719 // a fetch needs to have the image extracted first
2720 if (builder.isSampledImage(params.sampler))
2721 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2722 }
2723
John Kessenichfc51d282015-08-19 13:34:18 -06002724 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002725
John Kessenichfc51d282015-08-19 13:34:18 -06002726 params.coords = arguments[1];
2727 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002728 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002729
2730 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002731 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002732 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002733 ++extraArgs;
2734 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002735 params.Dref = arguments[2];
2736 ++extraArgs;
2737 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002738 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002739 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002740 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002741 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002742 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002743 dRefComp = builder.getNumComponents(params.coords) - 1;
2744 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002745 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2746 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002747
2748 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002749 if (cracked.lod) {
2750 params.lod = arguments[2];
2751 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002752 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2753 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2754 noImplicitLod = true;
2755 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002756
2757 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002758 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002759 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002760 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002761 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002762
2763 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002764 if (cracked.grad) {
2765 params.gradX = arguments[2 + extraArgs];
2766 params.gradY = arguments[3 + extraArgs];
2767 extraArgs += 2;
2768 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002769
2770 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002771 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002772 params.offset = arguments[2 + extraArgs];
2773 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002774 } else if (cracked.offsets) {
2775 params.offsets = arguments[2 + extraArgs];
2776 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002777 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002778
2779 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002780 if (cracked.lodClamp) {
2781 params.lodClamp = arguments[2 + extraArgs];
2782 ++extraArgs;
2783 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002784
2785 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002786 if (sparse) {
2787 params.texelOut = arguments[2 + extraArgs];
2788 ++extraArgs;
2789 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002790
2791 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002792 if (bias) {
2793 params.bias = arguments[2 + extraArgs];
2794 ++extraArgs;
2795 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002796
2797 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002798 if (cracked.gather && ! sampler.shadow) {
2799 // default component is 0, if missing, otherwise an argument
2800 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002801 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002802 ++extraArgs;
2803 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002804 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002805 }
2806 }
John Kessenichfc51d282015-08-19 13:34:18 -06002807
John Kessenich65336482016-06-16 14:06:26 -06002808 // projective component (might not to move)
2809 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2810 // are divided by the last component of P."
2811 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2812 // unused components will appear after all used components."
2813 if (cracked.proj) {
2814 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2815 int projTargetComp;
2816 switch (sampler.dim) {
2817 case glslang::Esd1D: projTargetComp = 1; break;
2818 case glslang::Esd2D: projTargetComp = 2; break;
2819 case glslang::EsdRect: projTargetComp = 2; break;
2820 default: projTargetComp = projSourceComp; break;
2821 }
2822 // copy the projective coordinate if we have to
2823 if (projTargetComp != projSourceComp) {
2824 spv::Id projComp = builder.createCompositeExtract(params.coords,
2825 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2826 projSourceComp);
2827 params.coords = builder.createCompositeInsert(projComp, params.coords,
2828 builder.getTypeId(params.coords), projTargetComp);
2829 }
2830 }
2831
John Kessenich8c8505c2016-07-26 12:50:38 -06002832 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002833}
2834
2835spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2836{
2837 // Grab the function's pointer from the previously created function
2838 spv::Function* function = functionMap[node->getName().c_str()];
2839 if (! function)
2840 return 0;
2841
2842 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2843 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2844
2845 // See comments in makeFunctions() for details about the semantics for parameter passing.
2846 //
2847 // These imply we need a four step process:
2848 // 1. Evaluate the arguments
2849 // 2. Allocate and make copies of in, out, and inout arguments
2850 // 3. Make the call
2851 // 4. Copy back the results
2852
2853 // 1. Evaluate the arguments
2854 std::vector<spv::Builder::AccessChain> lValues;
2855 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002856 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002857 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002858 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002859 // build l-value
2860 builder.clearAccessChain();
2861 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002862 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002863 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2864 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002865 // save l-value
2866 lValues.push_back(builder.getAccessChain());
2867 } else {
2868 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002869 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002870 }
2871 }
2872
2873 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2874 // copy the original into that space.
2875 //
2876 // Also, build up the list of actual arguments to pass in for the call
2877 int lValueCount = 0;
2878 int rValueCount = 0;
2879 std::vector<spv::Id> spvArgs;
2880 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002881 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002882 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002883 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002884 builder.setAccessChain(lValues[lValueCount]);
2885 arg = builder.accessChainGetLValue();
2886 ++lValueCount;
2887 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002888 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002889 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2890 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2891 // need to copy the input into output space
2892 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002893 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002894 builder.createStore(copy, arg);
2895 }
2896 ++lValueCount;
2897 } else {
2898 arg = rValues[rValueCount];
2899 ++rValueCount;
2900 }
2901 spvArgs.push_back(arg);
2902 }
2903
2904 // 3. Make the call.
2905 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002906 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002907
2908 // 4. Copy back out an "out" arguments.
2909 lValueCount = 0;
2910 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2911 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2912 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2913 spv::Id copy = builder.createLoad(spvArgs[a]);
2914 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002915 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002916 }
2917 ++lValueCount;
2918 }
2919 }
2920
2921 return result;
2922}
2923
2924// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002925spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2926 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002927 spv::Id typeId, spv::Id left, spv::Id right,
2928 glslang::TBasicType typeProxy, bool reduceComparison)
2929{
Rex Xu8ff43de2016-04-22 16:51:45 +08002930 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002931 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002932 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002933
2934 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002935 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002936 bool comparison = false;
2937
2938 switch (op) {
2939 case glslang::EOpAdd:
2940 case glslang::EOpAddAssign:
2941 if (isFloat)
2942 binOp = spv::OpFAdd;
2943 else
2944 binOp = spv::OpIAdd;
2945 break;
2946 case glslang::EOpSub:
2947 case glslang::EOpSubAssign:
2948 if (isFloat)
2949 binOp = spv::OpFSub;
2950 else
2951 binOp = spv::OpISub;
2952 break;
2953 case glslang::EOpMul:
2954 case glslang::EOpMulAssign:
2955 if (isFloat)
2956 binOp = spv::OpFMul;
2957 else
2958 binOp = spv::OpIMul;
2959 break;
2960 case glslang::EOpVectorTimesScalar:
2961 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002962 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002963 if (builder.isVector(right))
2964 std::swap(left, right);
2965 assert(builder.isScalar(right));
2966 needMatchingVectors = false;
2967 binOp = spv::OpVectorTimesScalar;
2968 } else
2969 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002970 break;
2971 case glslang::EOpVectorTimesMatrix:
2972 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002973 binOp = spv::OpVectorTimesMatrix;
2974 break;
2975 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002976 binOp = spv::OpMatrixTimesVector;
2977 break;
2978 case glslang::EOpMatrixTimesScalar:
2979 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002980 binOp = spv::OpMatrixTimesScalar;
2981 break;
2982 case glslang::EOpMatrixTimesMatrix:
2983 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002984 binOp = spv::OpMatrixTimesMatrix;
2985 break;
2986 case glslang::EOpOuterProduct:
2987 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002988 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002989 break;
2990
2991 case glslang::EOpDiv:
2992 case glslang::EOpDivAssign:
2993 if (isFloat)
2994 binOp = spv::OpFDiv;
2995 else if (isUnsigned)
2996 binOp = spv::OpUDiv;
2997 else
2998 binOp = spv::OpSDiv;
2999 break;
3000 case glslang::EOpMod:
3001 case glslang::EOpModAssign:
3002 if (isFloat)
3003 binOp = spv::OpFMod;
3004 else if (isUnsigned)
3005 binOp = spv::OpUMod;
3006 else
3007 binOp = spv::OpSMod;
3008 break;
3009 case glslang::EOpRightShift:
3010 case glslang::EOpRightShiftAssign:
3011 if (isUnsigned)
3012 binOp = spv::OpShiftRightLogical;
3013 else
3014 binOp = spv::OpShiftRightArithmetic;
3015 break;
3016 case glslang::EOpLeftShift:
3017 case glslang::EOpLeftShiftAssign:
3018 binOp = spv::OpShiftLeftLogical;
3019 break;
3020 case glslang::EOpAnd:
3021 case glslang::EOpAndAssign:
3022 binOp = spv::OpBitwiseAnd;
3023 break;
3024 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003025 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 binOp = spv::OpLogicalAnd;
3027 break;
3028 case glslang::EOpInclusiveOr:
3029 case glslang::EOpInclusiveOrAssign:
3030 binOp = spv::OpBitwiseOr;
3031 break;
3032 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003033 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003034 binOp = spv::OpLogicalOr;
3035 break;
3036 case glslang::EOpExclusiveOr:
3037 case glslang::EOpExclusiveOrAssign:
3038 binOp = spv::OpBitwiseXor;
3039 break;
3040 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003041 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003042 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003043 break;
3044
3045 case glslang::EOpLessThan:
3046 case glslang::EOpGreaterThan:
3047 case glslang::EOpLessThanEqual:
3048 case glslang::EOpGreaterThanEqual:
3049 case glslang::EOpEqual:
3050 case glslang::EOpNotEqual:
3051 case glslang::EOpVectorEqual:
3052 case glslang::EOpVectorNotEqual:
3053 comparison = true;
3054 break;
3055 default:
3056 break;
3057 }
3058
John Kessenich7c1aa102015-10-15 13:29:11 -06003059 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003060 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003061 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003062 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003063 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003064
3065 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003066 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003067 builder.promoteScalar(precision, left, right);
3068
qining25262b32016-05-06 17:25:16 -04003069 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3070 addDecoration(result, noContraction);
3071 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003072 }
3073
3074 if (! comparison)
3075 return 0;
3076
John Kessenich7c1aa102015-10-15 13:29:11 -06003077 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003078
3079 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
3080 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
3081
John Kessenich22118352015-12-21 20:54:09 -07003082 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003083 }
3084
3085 switch (op) {
3086 case glslang::EOpLessThan:
3087 if (isFloat)
3088 binOp = spv::OpFOrdLessThan;
3089 else if (isUnsigned)
3090 binOp = spv::OpULessThan;
3091 else
3092 binOp = spv::OpSLessThan;
3093 break;
3094 case glslang::EOpGreaterThan:
3095 if (isFloat)
3096 binOp = spv::OpFOrdGreaterThan;
3097 else if (isUnsigned)
3098 binOp = spv::OpUGreaterThan;
3099 else
3100 binOp = spv::OpSGreaterThan;
3101 break;
3102 case glslang::EOpLessThanEqual:
3103 if (isFloat)
3104 binOp = spv::OpFOrdLessThanEqual;
3105 else if (isUnsigned)
3106 binOp = spv::OpULessThanEqual;
3107 else
3108 binOp = spv::OpSLessThanEqual;
3109 break;
3110 case glslang::EOpGreaterThanEqual:
3111 if (isFloat)
3112 binOp = spv::OpFOrdGreaterThanEqual;
3113 else if (isUnsigned)
3114 binOp = spv::OpUGreaterThanEqual;
3115 else
3116 binOp = spv::OpSGreaterThanEqual;
3117 break;
3118 case glslang::EOpEqual:
3119 case glslang::EOpVectorEqual:
3120 if (isFloat)
3121 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003122 else if (isBool)
3123 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 else
3125 binOp = spv::OpIEqual;
3126 break;
3127 case glslang::EOpNotEqual:
3128 case glslang::EOpVectorNotEqual:
3129 if (isFloat)
3130 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003131 else if (isBool)
3132 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 else
3134 binOp = spv::OpINotEqual;
3135 break;
3136 default:
3137 break;
3138 }
3139
qining25262b32016-05-06 17:25:16 -04003140 if (binOp != spv::OpNop) {
3141 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3142 addDecoration(result, noContraction);
3143 return builder.setPrecision(result, precision);
3144 }
John Kessenich140f3df2015-06-26 16:58:36 -06003145
3146 return 0;
3147}
3148
John Kessenich04bb8a02015-12-12 12:28:14 -07003149//
3150// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3151// These can be any of:
3152//
3153// matrix * scalar
3154// scalar * matrix
3155// matrix * matrix linear algebraic
3156// matrix * vector
3157// vector * matrix
3158// matrix * matrix componentwise
3159// matrix op matrix op in {+, -, /}
3160// matrix op scalar op in {+, -, /}
3161// scalar op matrix op in {+, -, /}
3162//
qining25262b32016-05-06 17:25:16 -04003163spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003164{
3165 bool firstClass = true;
3166
3167 // First, handle first-class matrix operations (* and matrix/scalar)
3168 switch (op) {
3169 case spv::OpFDiv:
3170 if (builder.isMatrix(left) && builder.isScalar(right)) {
3171 // turn matrix / scalar into a multiply...
3172 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3173 op = spv::OpMatrixTimesScalar;
3174 } else
3175 firstClass = false;
3176 break;
3177 case spv::OpMatrixTimesScalar:
3178 if (builder.isMatrix(right))
3179 std::swap(left, right);
3180 assert(builder.isScalar(right));
3181 break;
3182 case spv::OpVectorTimesMatrix:
3183 assert(builder.isVector(left));
3184 assert(builder.isMatrix(right));
3185 break;
3186 case spv::OpMatrixTimesVector:
3187 assert(builder.isMatrix(left));
3188 assert(builder.isVector(right));
3189 break;
3190 case spv::OpMatrixTimesMatrix:
3191 assert(builder.isMatrix(left));
3192 assert(builder.isMatrix(right));
3193 break;
3194 default:
3195 firstClass = false;
3196 break;
3197 }
3198
qining25262b32016-05-06 17:25:16 -04003199 if (firstClass) {
3200 spv::Id result = builder.createBinOp(op, typeId, left, right);
3201 addDecoration(result, noContraction);
3202 return builder.setPrecision(result, precision);
3203 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003204
LoopDawg592860c2016-06-09 08:57:35 -06003205 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003206 // The result type of all of them is the same type as the (a) matrix operand.
3207 // The algorithm is to:
3208 // - break the matrix(es) into vectors
3209 // - smear any scalar to a vector
3210 // - do vector operations
3211 // - make a matrix out the vector results
3212 switch (op) {
3213 case spv::OpFAdd:
3214 case spv::OpFSub:
3215 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003216 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003217 case spv::OpFMul:
3218 {
3219 // one time set up...
3220 bool leftMat = builder.isMatrix(left);
3221 bool rightMat = builder.isMatrix(right);
3222 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3223 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3224 spv::Id scalarType = builder.getScalarTypeId(typeId);
3225 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3226 std::vector<spv::Id> results;
3227 spv::Id smearVec = spv::NoResult;
3228 if (builder.isScalar(left))
3229 smearVec = builder.smearScalar(precision, left, vecType);
3230 else if (builder.isScalar(right))
3231 smearVec = builder.smearScalar(precision, right, vecType);
3232
3233 // do each vector op
3234 for (unsigned int c = 0; c < numCols; ++c) {
3235 std::vector<unsigned int> indexes;
3236 indexes.push_back(c);
3237 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3238 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003239 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3240 addDecoration(result, noContraction);
3241 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003242 }
3243
3244 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003245 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003246 }
3247 default:
3248 assert(0);
3249 return spv::NoResult;
3250 }
3251}
3252
qining25262b32016-05-06 17:25:16 -04003253spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003254{
3255 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003256 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003257 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003258 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003259 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003260
3261 switch (op) {
3262 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003263 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003264 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003265 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003266 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003267 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003268 unaryOp = spv::OpSNegate;
3269 break;
3270
3271 case glslang::EOpLogicalNot:
3272 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003273 unaryOp = spv::OpLogicalNot;
3274 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003275 case glslang::EOpBitwiseNot:
3276 unaryOp = spv::OpNot;
3277 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003278
John Kessenich140f3df2015-06-26 16:58:36 -06003279 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003280 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003281 break;
3282 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003283 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003284 break;
3285 case glslang::EOpTranspose:
3286 unaryOp = spv::OpTranspose;
3287 break;
3288
3289 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003290 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003291 break;
3292 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003293 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003294 break;
3295 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003296 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003297 break;
3298 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003299 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003300 break;
3301 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003302 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003303 break;
3304 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003305 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003306 break;
3307 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003308 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003309 break;
3310 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003311 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003312 break;
3313
3314 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003315 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003316 break;
3317 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003318 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003319 break;
3320 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003321 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003322 break;
3323 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003324 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003325 break;
3326 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003328 break;
3329 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003330 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003331 break;
3332
3333 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003334 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003335 break;
3336 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003337 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003338 break;
3339
3340 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003341 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003342 break;
3343 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003344 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003345 break;
3346 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003350 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003351 break;
3352 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003353 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003354 break;
3355 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003356 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003357 break;
3358
3359 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003360 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003361 break;
3362 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003363 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003364 break;
3365 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003366 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003367 break;
3368 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003369 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003370 break;
3371 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003372 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 break;
3374 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003375 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003376 break;
3377
3378 case glslang::EOpIsNan:
3379 unaryOp = spv::OpIsNan;
3380 break;
3381 case glslang::EOpIsInf:
3382 unaryOp = spv::OpIsInf;
3383 break;
LoopDawg592860c2016-06-09 08:57:35 -06003384 case glslang::EOpIsFinite:
3385 unaryOp = spv::OpIsFinite;
3386 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003387
Rex Xucbc426e2015-12-15 16:03:10 +08003388 case glslang::EOpFloatBitsToInt:
3389 case glslang::EOpFloatBitsToUint:
3390 case glslang::EOpIntBitsToFloat:
3391 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003392 case glslang::EOpDoubleBitsToInt64:
3393 case glslang::EOpDoubleBitsToUint64:
3394 case glslang::EOpInt64BitsToDouble:
3395 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003396 unaryOp = spv::OpBitcast;
3397 break;
3398
John Kessenich140f3df2015-06-26 16:58:36 -06003399 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003400 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
3402 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003403 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003404 break;
3405 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003410 break;
3411 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003415 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003417 case glslang::EOpPackSnorm4x8:
3418 libCall = spv::GLSLstd450PackSnorm4x8;
3419 break;
3420 case glslang::EOpUnpackSnorm4x8:
3421 libCall = spv::GLSLstd450UnpackSnorm4x8;
3422 break;
3423 case glslang::EOpPackUnorm4x8:
3424 libCall = spv::GLSLstd450PackUnorm4x8;
3425 break;
3426 case glslang::EOpUnpackUnorm4x8:
3427 libCall = spv::GLSLstd450UnpackUnorm4x8;
3428 break;
3429 case glslang::EOpPackDouble2x32:
3430 libCall = spv::GLSLstd450PackDouble2x32;
3431 break;
3432 case glslang::EOpUnpackDouble2x32:
3433 libCall = spv::GLSLstd450UnpackDouble2x32;
3434 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003435
Rex Xu8ff43de2016-04-22 16:51:45 +08003436 case glslang::EOpPackInt2x32:
3437 case glslang::EOpUnpackInt2x32:
3438 case glslang::EOpPackUint2x32:
3439 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003440 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003441 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3442 break;
3443
John Kessenich140f3df2015-06-26 16:58:36 -06003444 case glslang::EOpDPdx:
3445 unaryOp = spv::OpDPdx;
3446 break;
3447 case glslang::EOpDPdy:
3448 unaryOp = spv::OpDPdy;
3449 break;
3450 case glslang::EOpFwidth:
3451 unaryOp = spv::OpFwidth;
3452 break;
3453 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003454 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003455 unaryOp = spv::OpDPdxFine;
3456 break;
3457 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003458 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003459 unaryOp = spv::OpDPdyFine;
3460 break;
3461 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003462 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003463 unaryOp = spv::OpFwidthFine;
3464 break;
3465 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003466 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003467 unaryOp = spv::OpDPdxCoarse;
3468 break;
3469 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003470 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003471 unaryOp = spv::OpDPdyCoarse;
3472 break;
3473 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003474 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003475 unaryOp = spv::OpFwidthCoarse;
3476 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003477 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003478 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003479 libCall = spv::GLSLstd450InterpolateAtCentroid;
3480 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003481 case glslang::EOpAny:
3482 unaryOp = spv::OpAny;
3483 break;
3484 case glslang::EOpAll:
3485 unaryOp = spv::OpAll;
3486 break;
3487
3488 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003489 if (isFloat)
3490 libCall = spv::GLSLstd450FAbs;
3491 else
3492 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003493 break;
3494 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 if (isFloat)
3496 libCall = spv::GLSLstd450FSign;
3497 else
3498 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500
John Kessenichfc51d282015-08-19 13:34:18 -06003501 case glslang::EOpAtomicCounterIncrement:
3502 case glslang::EOpAtomicCounterDecrement:
3503 case glslang::EOpAtomicCounter:
3504 {
3505 // Handle all of the atomics in one place, in createAtomicOperation()
3506 std::vector<spv::Id> operands;
3507 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003508 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003509 }
3510
John Kessenichfc51d282015-08-19 13:34:18 -06003511 case glslang::EOpBitFieldReverse:
3512 unaryOp = spv::OpBitReverse;
3513 break;
3514 case glslang::EOpBitCount:
3515 unaryOp = spv::OpBitCount;
3516 break;
3517 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003518 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003519 break;
3520 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003521 if (isUnsigned)
3522 libCall = spv::GLSLstd450FindUMsb;
3523 else
3524 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003525 break;
3526
Rex Xu574ab042016-04-14 16:53:07 +08003527 case glslang::EOpBallot:
3528 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003529 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003530 libCall = spv::GLSLstd450Bad;
3531 break;
3532
Rex Xu338b1852016-05-05 20:38:33 +08003533 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003534 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003535 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003536#ifdef AMD_EXTENSIONS
3537 case glslang::EOpMinInvocations:
3538 case glslang::EOpMaxInvocations:
3539 case glslang::EOpAddInvocations:
3540 case glslang::EOpMinInvocationsNonUniform:
3541 case glslang::EOpMaxInvocationsNonUniform:
3542 case glslang::EOpAddInvocationsNonUniform:
3543#endif
3544 return createInvocationsOperation(op, typeId, operand, typeProxy);
3545
3546#ifdef AMD_EXTENSIONS
3547 case glslang::EOpMbcnt:
3548 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3549 libCall = spv::MbcntAMD;
3550 break;
3551
3552 case glslang::EOpCubeFaceIndex:
3553 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3554 libCall = spv::CubeFaceIndexAMD;
3555 break;
3556
3557 case glslang::EOpCubeFaceCoord:
3558 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3559 libCall = spv::CubeFaceCoordAMD;
3560 break;
3561#endif
Rex Xu338b1852016-05-05 20:38:33 +08003562
John Kessenich140f3df2015-06-26 16:58:36 -06003563 default:
3564 return 0;
3565 }
3566
3567 spv::Id id;
3568 if (libCall >= 0) {
3569 std::vector<spv::Id> args;
3570 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003571 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003572 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003573 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003574 }
John Kessenich140f3df2015-06-26 16:58:36 -06003575
qining25262b32016-05-06 17:25:16 -04003576 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003577 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003578}
3579
John Kessenich7a53f762016-01-20 11:19:27 -07003580// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003581spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07003582{
3583 // Handle unary operations vector by vector.
3584 // The result type is the same type as the original type.
3585 // The algorithm is to:
3586 // - break the matrix into vectors
3587 // - apply the operation to each vector
3588 // - make a matrix out the vector results
3589
3590 // get the types sorted out
3591 int numCols = builder.getNumColumns(operand);
3592 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003593 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3594 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003595 std::vector<spv::Id> results;
3596
3597 // do each vector op
3598 for (int c = 0; c < numCols; ++c) {
3599 std::vector<unsigned int> indexes;
3600 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003601 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3602 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3603 addDecoration(destVec, noContraction);
3604 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003605 }
3606
3607 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003608 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003609}
3610
Rex Xu73e3ce72016-04-27 18:48:17 +08003611spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003612{
3613 spv::Op convOp = spv::OpNop;
3614 spv::Id zero = 0;
3615 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003616 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003617
3618 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3619
3620 switch (op) {
3621 case glslang::EOpConvIntToBool:
3622 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003623 case glslang::EOpConvInt64ToBool:
3624 case glslang::EOpConvUint64ToBool:
3625 zero = (op == glslang::EOpConvInt64ToBool ||
3626 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003627 zero = makeSmearedConstant(zero, vectorSize);
3628 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3629
3630 case glslang::EOpConvFloatToBool:
3631 zero = builder.makeFloatConstant(0.0F);
3632 zero = makeSmearedConstant(zero, vectorSize);
3633 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3634
3635 case glslang::EOpConvDoubleToBool:
3636 zero = builder.makeDoubleConstant(0.0);
3637 zero = makeSmearedConstant(zero, vectorSize);
3638 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3639
3640 case glslang::EOpConvBoolToFloat:
3641 convOp = spv::OpSelect;
3642 zero = builder.makeFloatConstant(0.0);
3643 one = builder.makeFloatConstant(1.0);
3644 break;
3645 case glslang::EOpConvBoolToDouble:
3646 convOp = spv::OpSelect;
3647 zero = builder.makeDoubleConstant(0.0);
3648 one = builder.makeDoubleConstant(1.0);
3649 break;
3650 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003651 case glslang::EOpConvBoolToInt64:
3652 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3653 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003654 convOp = spv::OpSelect;
3655 break;
3656 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003657 case glslang::EOpConvBoolToUint64:
3658 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3659 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003660 convOp = spv::OpSelect;
3661 break;
3662
3663 case glslang::EOpConvIntToFloat:
3664 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003665 case glslang::EOpConvInt64ToFloat:
3666 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003667 convOp = spv::OpConvertSToF;
3668 break;
3669
3670 case glslang::EOpConvUintToFloat:
3671 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003672 case glslang::EOpConvUint64ToFloat:
3673 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003674 convOp = spv::OpConvertUToF;
3675 break;
3676
3677 case glslang::EOpConvDoubleToFloat:
3678 case glslang::EOpConvFloatToDouble:
3679 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003680 if (builder.isMatrixType(destType))
3681 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003682 break;
3683
3684 case glslang::EOpConvFloatToInt:
3685 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003686 case glslang::EOpConvFloatToInt64:
3687 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003688 convOp = spv::OpConvertFToS;
3689 break;
3690
3691 case glslang::EOpConvUintToInt:
3692 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003693 case glslang::EOpConvUint64ToInt64:
3694 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003695 if (builder.isInSpecConstCodeGenMode()) {
3696 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003697 zero = (op == glslang::EOpConvUintToInt64 ||
3698 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003699 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003700 // Use OpIAdd, instead of OpBitcast to do the conversion when
3701 // generating for OpSpecConstantOp instruction.
3702 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3703 }
3704 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003705 convOp = spv::OpBitcast;
3706 break;
3707
3708 case glslang::EOpConvFloatToUint:
3709 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003710 case glslang::EOpConvFloatToUint64:
3711 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003712 convOp = spv::OpConvertFToU;
3713 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003714
3715 case glslang::EOpConvIntToInt64:
3716 case glslang::EOpConvInt64ToInt:
3717 convOp = spv::OpSConvert;
3718 break;
3719
3720 case glslang::EOpConvUintToUint64:
3721 case glslang::EOpConvUint64ToUint:
3722 convOp = spv::OpUConvert;
3723 break;
3724
3725 case glslang::EOpConvIntToUint64:
3726 case glslang::EOpConvInt64ToUint:
3727 case glslang::EOpConvUint64ToInt:
3728 case glslang::EOpConvUintToInt64:
3729 // OpSConvert/OpUConvert + OpBitCast
3730 switch (op) {
3731 case glslang::EOpConvIntToUint64:
3732 convOp = spv::OpSConvert;
3733 type = builder.makeIntType(64);
3734 break;
3735 case glslang::EOpConvInt64ToUint:
3736 convOp = spv::OpSConvert;
3737 type = builder.makeIntType(32);
3738 break;
3739 case glslang::EOpConvUint64ToInt:
3740 convOp = spv::OpUConvert;
3741 type = builder.makeUintType(32);
3742 break;
3743 case glslang::EOpConvUintToInt64:
3744 convOp = spv::OpUConvert;
3745 type = builder.makeUintType(64);
3746 break;
3747 default:
3748 assert(0);
3749 break;
3750 }
3751
3752 if (vectorSize > 0)
3753 type = builder.makeVectorType(type, vectorSize);
3754
3755 operand = builder.createUnaryOp(convOp, type, operand);
3756
3757 if (builder.isInSpecConstCodeGenMode()) {
3758 // Build zero scalar or vector for OpIAdd.
3759 zero = (op == glslang::EOpConvIntToUint64 ||
3760 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3761 zero = makeSmearedConstant(zero, vectorSize);
3762 // Use OpIAdd, instead of OpBitcast to do the conversion when
3763 // generating for OpSpecConstantOp instruction.
3764 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3765 }
3766 // For normal run-time conversion instruction, use OpBitcast.
3767 convOp = spv::OpBitcast;
3768 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003769 default:
3770 break;
3771 }
3772
3773 spv::Id result = 0;
3774 if (convOp == spv::OpNop)
3775 return result;
3776
3777 if (convOp == spv::OpSelect) {
3778 zero = makeSmearedConstant(zero, vectorSize);
3779 one = makeSmearedConstant(one, vectorSize);
3780 result = builder.createTriOp(convOp, destType, operand, one, zero);
3781 } else
3782 result = builder.createUnaryOp(convOp, destType, operand);
3783
John Kessenich32cfd492016-02-02 12:37:46 -07003784 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003785}
3786
3787spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3788{
3789 if (vectorSize == 0)
3790 return constant;
3791
3792 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3793 std::vector<spv::Id> components;
3794 for (int c = 0; c < vectorSize; ++c)
3795 components.push_back(constant);
3796 return builder.makeCompositeConstant(vectorTypeId, components);
3797}
3798
John Kessenich426394d2015-07-23 10:22:48 -06003799// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003800spv::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 -06003801{
3802 spv::Op opCode = spv::OpNop;
3803
3804 switch (op) {
3805 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003806 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003807 opCode = spv::OpAtomicIAdd;
3808 break;
3809 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003810 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003811 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003812 break;
3813 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003814 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003815 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003816 break;
3817 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003818 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003819 opCode = spv::OpAtomicAnd;
3820 break;
3821 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003822 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003823 opCode = spv::OpAtomicOr;
3824 break;
3825 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003826 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003827 opCode = spv::OpAtomicXor;
3828 break;
3829 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003830 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003831 opCode = spv::OpAtomicExchange;
3832 break;
3833 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003834 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003835 opCode = spv::OpAtomicCompareExchange;
3836 break;
3837 case glslang::EOpAtomicCounterIncrement:
3838 opCode = spv::OpAtomicIIncrement;
3839 break;
3840 case glslang::EOpAtomicCounterDecrement:
3841 opCode = spv::OpAtomicIDecrement;
3842 break;
3843 case glslang::EOpAtomicCounter:
3844 opCode = spv::OpAtomicLoad;
3845 break;
3846 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003847 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003848 break;
3849 }
3850
3851 // Sort out the operands
3852 // - mapping from glslang -> SPV
3853 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003854 // - compare-exchange swaps the value and comparator
3855 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003856 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3857 auto opIt = operands.begin(); // walk the glslang operands
3858 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003859 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3860 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3861 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003862 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3863 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003864 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003865 spvAtomicOperands.push_back(*(opIt + 1));
3866 spvAtomicOperands.push_back(*opIt);
3867 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003868 }
John Kessenich426394d2015-07-23 10:22:48 -06003869
John Kessenich3e60a6f2015-09-14 22:45:16 -06003870 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003871 for (; opIt != operands.end(); ++opIt)
3872 spvAtomicOperands.push_back(*opIt);
3873
3874 return builder.createOp(opCode, typeId, spvAtomicOperands);
3875}
3876
John Kessenich91cef522016-05-05 16:45:40 -06003877// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003878spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003879{
Rex Xu9d93a232016-05-05 12:30:44 +08003880 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3881 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3882
John Kessenich91cef522016-05-05 16:45:40 -06003883 builder.addCapability(spv::CapabilityGroups);
3884
3885 std::vector<spv::Id> operands;
3886 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003887#ifdef AMD_EXTENSIONS
3888 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3889 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3890 operands.push_back(spv::GroupOperationReduce);
3891#endif
John Kessenich91cef522016-05-05 16:45:40 -06003892 operands.push_back(operand);
3893
3894 switch (op) {
3895 case glslang::EOpAnyInvocation:
3896 case glslang::EOpAllInvocations:
3897 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3898
3899 case glslang::EOpAllInvocationsEqual:
3900 {
3901 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3902 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3903
3904 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3905 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3906 }
Rex Xu9d93a232016-05-05 12:30:44 +08003907#ifdef AMD_EXTENSIONS
3908 case glslang::EOpMinInvocations:
3909 case glslang::EOpMaxInvocations:
3910 case glslang::EOpAddInvocations:
3911 {
3912 spv::Op spvOp = spv::OpNop;
3913 if (op == glslang::EOpMinInvocations) {
3914 if (isFloat)
3915 spvOp = spv::OpGroupFMin;
3916 else {
3917 if (isUnsigned)
3918 spvOp = spv::OpGroupUMin;
3919 else
3920 spvOp = spv::OpGroupSMin;
3921 }
3922 } else if (op == glslang::EOpMaxInvocations) {
3923 if (isFloat)
3924 spvOp = spv::OpGroupFMax;
3925 else {
3926 if (isUnsigned)
3927 spvOp = spv::OpGroupUMax;
3928 else
3929 spvOp = spv::OpGroupSMax;
3930 }
3931 } else {
3932 if (isFloat)
3933 spvOp = spv::OpGroupFAdd;
3934 else
3935 spvOp = spv::OpGroupIAdd;
3936 }
3937
3938 return builder.createOp(spvOp, typeId, operands);
3939 }
3940 case glslang::EOpMinInvocationsNonUniform:
3941 case glslang::EOpMaxInvocationsNonUniform:
3942 case glslang::EOpAddInvocationsNonUniform:
3943 {
3944 spv::Op spvOp = spv::OpNop;
3945 if (op == glslang::EOpMinInvocationsNonUniform) {
3946 if (isFloat)
3947 spvOp = spv::OpGroupFMinNonUniformAMD;
3948 else {
3949 if (isUnsigned)
3950 spvOp = spv::OpGroupUMinNonUniformAMD;
3951 else
3952 spvOp = spv::OpGroupSMinNonUniformAMD;
3953 }
3954 }
3955 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3956 if (isFloat)
3957 spvOp = spv::OpGroupFMaxNonUniformAMD;
3958 else {
3959 if (isUnsigned)
3960 spvOp = spv::OpGroupUMaxNonUniformAMD;
3961 else
3962 spvOp = spv::OpGroupSMaxNonUniformAMD;
3963 }
3964 }
3965 else {
3966 if (isFloat)
3967 spvOp = spv::OpGroupFAddNonUniformAMD;
3968 else
3969 spvOp = spv::OpGroupIAddNonUniformAMD;
3970 }
3971
3972 return builder.createOp(spvOp, typeId, operands);
3973 }
3974#endif
John Kessenich91cef522016-05-05 16:45:40 -06003975 default:
3976 logger->missingFunctionality("invocation operation");
3977 return spv::NoResult;
3978 }
3979}
3980
John Kessenich5e4b1242015-08-06 22:53:06 -06003981spv::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 -06003982{
Rex Xu8ff43de2016-04-22 16:51:45 +08003983 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003984 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3985
John Kessenich140f3df2015-06-26 16:58:36 -06003986 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003987 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003988 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003989 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003990 spv::Id typeId0 = 0;
3991 if (consumedOperands > 0)
3992 typeId0 = builder.getTypeId(operands[0]);
3993 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003994
3995 switch (op) {
3996 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003997 if (isFloat)
3998 libCall = spv::GLSLstd450FMin;
3999 else if (isUnsigned)
4000 libCall = spv::GLSLstd450UMin;
4001 else
4002 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004003 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004004 break;
4005 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004007 break;
4008 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004009 if (isFloat)
4010 libCall = spv::GLSLstd450FMax;
4011 else if (isUnsigned)
4012 libCall = spv::GLSLstd450UMax;
4013 else
4014 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004015 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004016 break;
4017 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004018 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004019 break;
4020 case glslang::EOpDot:
4021 opCode = spv::OpDot;
4022 break;
4023 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004024 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004025 break;
4026
4027 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004028 if (isFloat)
4029 libCall = spv::GLSLstd450FClamp;
4030 else if (isUnsigned)
4031 libCall = spv::GLSLstd450UClamp;
4032 else
4033 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004034 builder.promoteScalar(precision, operands.front(), operands[1]);
4035 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004036 break;
4037 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004038 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4039 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004040 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004041 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004042 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004043 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004044 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004045 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004046 break;
4047 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004048 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004049 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004053 builder.promoteScalar(precision, operands[0], operands[2]);
4054 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004055 break;
4056
4057 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 break;
4063 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004064 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004065 break;
4066 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 break;
4069 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004072 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004073 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004074 libCall = spv::GLSLstd450InterpolateAtSample;
4075 break;
4076 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004077 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004078 libCall = spv::GLSLstd450InterpolateAtOffset;
4079 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004080 case glslang::EOpAddCarry:
4081 opCode = spv::OpIAddCarry;
4082 typeId = builder.makeStructResultType(typeId0, typeId0);
4083 consumedOperands = 2;
4084 break;
4085 case glslang::EOpSubBorrow:
4086 opCode = spv::OpISubBorrow;
4087 typeId = builder.makeStructResultType(typeId0, typeId0);
4088 consumedOperands = 2;
4089 break;
4090 case glslang::EOpUMulExtended:
4091 opCode = spv::OpUMulExtended;
4092 typeId = builder.makeStructResultType(typeId0, typeId0);
4093 consumedOperands = 2;
4094 break;
4095 case glslang::EOpIMulExtended:
4096 opCode = spv::OpSMulExtended;
4097 typeId = builder.makeStructResultType(typeId0, typeId0);
4098 consumedOperands = 2;
4099 break;
4100 case glslang::EOpBitfieldExtract:
4101 if (isUnsigned)
4102 opCode = spv::OpBitFieldUExtract;
4103 else
4104 opCode = spv::OpBitFieldSExtract;
4105 break;
4106 case glslang::EOpBitfieldInsert:
4107 opCode = spv::OpBitFieldInsert;
4108 break;
4109
4110 case glslang::EOpFma:
4111 libCall = spv::GLSLstd450Fma;
4112 break;
4113 case glslang::EOpFrexp:
4114 libCall = spv::GLSLstd450FrexpStruct;
4115 if (builder.getNumComponents(operands[0]) == 1)
4116 frexpIntType = builder.makeIntegerType(32, true);
4117 else
4118 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4119 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4120 consumedOperands = 1;
4121 break;
4122 case glslang::EOpLdexp:
4123 libCall = spv::GLSLstd450Ldexp;
4124 break;
4125
Rex Xu574ab042016-04-14 16:53:07 +08004126 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004127 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004128 libCall = spv::GLSLstd450Bad;
4129 break;
4130
Rex Xu9d93a232016-05-05 12:30:44 +08004131#ifdef AMD_EXTENSIONS
4132 case glslang::EOpSwizzleInvocations:
4133 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4134 libCall = spv::SwizzleInvocationsAMD;
4135 break;
4136 case glslang::EOpSwizzleInvocationsMasked:
4137 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4138 libCall = spv::SwizzleInvocationsMaskedAMD;
4139 break;
4140 case glslang::EOpWriteInvocation:
4141 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4142 libCall = spv::WriteInvocationAMD;
4143 break;
4144
4145 case glslang::EOpMin3:
4146 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4147 if (isFloat)
4148 libCall = spv::FMin3AMD;
4149 else {
4150 if (isUnsigned)
4151 libCall = spv::UMin3AMD;
4152 else
4153 libCall = spv::SMin3AMD;
4154 }
4155 break;
4156 case glslang::EOpMax3:
4157 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4158 if (isFloat)
4159 libCall = spv::FMax3AMD;
4160 else {
4161 if (isUnsigned)
4162 libCall = spv::UMax3AMD;
4163 else
4164 libCall = spv::SMax3AMD;
4165 }
4166 break;
4167 case glslang::EOpMid3:
4168 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4169 if (isFloat)
4170 libCall = spv::FMid3AMD;
4171 else {
4172 if (isUnsigned)
4173 libCall = spv::UMid3AMD;
4174 else
4175 libCall = spv::SMid3AMD;
4176 }
4177 break;
4178
4179 case glslang::EOpInterpolateAtVertex:
4180 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4181 libCall = spv::InterpolateAtVertexAMD;
4182 break;
4183#endif
4184
John Kessenich140f3df2015-06-26 16:58:36 -06004185 default:
4186 return 0;
4187 }
4188
4189 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004190 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004191 // Use an extended instruction from the standard library.
4192 // Construct the call arguments, without modifying the original operands vector.
4193 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4194 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004195 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004196 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004197 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004198 case 0:
4199 // should all be handled by visitAggregate and createNoArgOperation
4200 assert(0);
4201 return 0;
4202 case 1:
4203 // should all be handled by createUnaryOperation
4204 assert(0);
4205 return 0;
4206 case 2:
4207 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4208 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004209 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004210 // anything 3 or over doesn't have l-value operands, so all should be consumed
4211 assert(consumedOperands == operands.size());
4212 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004213 break;
4214 }
4215 }
4216
John Kessenich55e7d112015-11-15 21:33:39 -07004217 // Decode the return types that were structures
4218 switch (op) {
4219 case glslang::EOpAddCarry:
4220 case glslang::EOpSubBorrow:
4221 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4222 id = builder.createCompositeExtract(id, typeId0, 0);
4223 break;
4224 case glslang::EOpUMulExtended:
4225 case glslang::EOpIMulExtended:
4226 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4227 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4228 break;
4229 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004230 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004231 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4232 id = builder.createCompositeExtract(id, typeId0, 0);
4233 break;
4234 default:
4235 break;
4236 }
4237
John Kessenich32cfd492016-02-02 12:37:46 -07004238 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004239}
4240
Rex Xu9d93a232016-05-05 12:30:44 +08004241// Intrinsics with no arguments (or no return value, and no precision).
4242spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004243{
4244 // TODO: get the barrier operands correct
4245
4246 switch (op) {
4247 case glslang::EOpEmitVertex:
4248 builder.createNoResultOp(spv::OpEmitVertex);
4249 return 0;
4250 case glslang::EOpEndPrimitive:
4251 builder.createNoResultOp(spv::OpEndPrimitive);
4252 return 0;
4253 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004254 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004255 return 0;
4256 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004257 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004258 return 0;
4259 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004260 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004261 return 0;
4262 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004263 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004264 return 0;
4265 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004266 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004267 return 0;
4268 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004269 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004270 return 0;
4271 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004272 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004273 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004274 case glslang::EOpAllMemoryBarrierWithGroupSync:
4275 // Control barrier with non-"None" semantic is also a memory barrier.
4276 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4277 return 0;
4278 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4279 // Control barrier with non-"None" semantic is also a memory barrier.
4280 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4281 return 0;
4282 case glslang::EOpWorkgroupMemoryBarrier:
4283 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4284 return 0;
4285 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4286 // Control barrier with non-"None" semantic is also a memory barrier.
4287 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4288 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004289#ifdef AMD_EXTENSIONS
4290 case glslang::EOpTime:
4291 {
4292 std::vector<spv::Id> args; // Dummy arguments
4293 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4294 return builder.setPrecision(id, precision);
4295 }
4296#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004297 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004298 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004299 return 0;
4300 }
4301}
4302
4303spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4304{
John Kessenich2f273362015-07-18 22:34:27 -06004305 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004306 spv::Id id;
4307 if (symbolValues.end() != iter) {
4308 id = iter->second;
4309 return id;
4310 }
4311
4312 // it was not found, create it
4313 id = createSpvVariable(symbol);
4314 symbolValues[symbol->getId()] = id;
4315
Rex Xuc884b4a2016-06-29 15:03:44 +08004316 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004317 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004318 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004319 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004320 if (symbol->getType().getQualifier().hasSpecConstantId())
4321 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004322 if (symbol->getQualifier().hasIndex())
4323 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4324 if (symbol->getQualifier().hasComponent())
4325 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4326 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004327 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004328 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004329 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004330 if (symbol->getQualifier().hasXfbBuffer())
4331 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4332 if (symbol->getQualifier().hasXfbOffset())
4333 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4334 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004335 // atomic counters use this:
4336 if (symbol->getQualifier().hasOffset())
4337 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004338 }
4339
scygan2c864272016-05-18 18:09:17 +02004340 if (symbol->getQualifier().hasLocation())
4341 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004342 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004343 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004344 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004345 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004346 }
John Kessenich140f3df2015-06-26 16:58:36 -06004347 if (symbol->getQualifier().hasSet())
4348 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004349 else if (IsDescriptorResource(symbol->getType())) {
4350 // default to 0
4351 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4352 }
John Kessenich140f3df2015-06-26 16:58:36 -06004353 if (symbol->getQualifier().hasBinding())
4354 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004355 if (symbol->getQualifier().hasAttachment())
4356 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004357 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004358 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004359 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004360 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004361 if (symbol->getQualifier().hasXfbBuffer())
4362 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4363 }
4364
Rex Xu1da878f2016-02-21 20:59:01 +08004365 if (symbol->getType().isImage()) {
4366 std::vector<spv::Decoration> memory;
4367 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4368 for (unsigned int i = 0; i < memory.size(); ++i)
4369 addDecoration(id, memory[i]);
4370 }
4371
John Kessenich140f3df2015-06-26 16:58:36 -06004372 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004373 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004374 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004375 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004376
John Kessenich140f3df2015-06-26 16:58:36 -06004377 return id;
4378}
4379
John Kessenich55e7d112015-11-15 21:33:39 -07004380// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004381void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4382{
John Kessenich4016e382016-07-15 11:53:56 -06004383 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004384 builder.addDecoration(id, dec);
4385}
4386
John Kessenich55e7d112015-11-15 21:33:39 -07004387// If 'dec' is valid, add a one-operand decoration to an object
4388void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4389{
John Kessenich4016e382016-07-15 11:53:56 -06004390 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004391 builder.addDecoration(id, dec, value);
4392}
4393
4394// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004395void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4396{
John Kessenich4016e382016-07-15 11:53:56 -06004397 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004398 builder.addMemberDecoration(id, (unsigned)member, dec);
4399}
4400
John Kessenich92187592016-02-01 13:45:25 -07004401// If 'dec' is valid, add a one-operand decoration to a struct member
4402void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4403{
John Kessenich4016e382016-07-15 11:53:56 -06004404 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004405 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4406}
4407
John Kessenich55e7d112015-11-15 21:33:39 -07004408// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004409// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004410//
4411// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4412//
4413// Recursively walk the nodes. The nodes form a tree whose leaves are
4414// regular constants, which themselves are trees that createSpvConstant()
4415// recursively walks. So, this function walks the "top" of the tree:
4416// - emit specialization constant-building instructions for specConstant
4417// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004418spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004419{
John Kessenich7cc0e282016-03-20 00:46:02 -06004420 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004421
qining4f4bb812016-04-03 23:55:17 -04004422 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004423 if (! node.getQualifier().specConstant) {
4424 // hand off to the non-spec-constant path
4425 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4426 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004427 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004428 nextConst, false);
4429 }
4430
4431 // We now know we have a specialization constant to build
4432
John Kessenichd94c0032016-05-30 19:29:40 -06004433 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004434 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4435 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4436 std::vector<spv::Id> dimConstId;
4437 for (int dim = 0; dim < 3; ++dim) {
4438 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4439 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4440 if (specConst)
4441 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4442 }
4443 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4444 }
4445
4446 // An AST node labelled as specialization constant should be a symbol node.
4447 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4448 if (auto* sn = node.getAsSymbolNode()) {
4449 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004450 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4451 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4452 // will set the builder into spec constant op instruction generating mode.
4453 sub_tree->traverse(this);
4454 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004455 } else if (auto* const_union_array = &sn->getConstArray()){
4456 int nextConst = 0;
4457 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004458 }
4459 }
qining4f4bb812016-04-03 23:55:17 -04004460
4461 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4462 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004463 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004464 exit(1);
4465 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004466}
4467
John Kessenich140f3df2015-06-26 16:58:36 -06004468// Use 'consts' as the flattened glslang source of scalar constants to recursively
4469// build the aggregate SPIR-V constant.
4470//
4471// If there are not enough elements present in 'consts', 0 will be substituted;
4472// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4473//
qining08408382016-03-21 09:51:37 -04004474spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004475{
4476 // vector of constants for SPIR-V
4477 std::vector<spv::Id> spvConsts;
4478
4479 // Type is used for struct and array constants
4480 spv::Id typeId = convertGlslangToSpvType(glslangType);
4481
4482 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004483 glslang::TType elementType(glslangType, 0);
4484 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004485 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004486 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004487 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004488 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004489 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004490 } else if (glslangType.getStruct()) {
4491 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4492 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004493 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004494 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004495 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4496 bool zero = nextConst >= consts.size();
4497 switch (glslangType.getBasicType()) {
4498 case glslang::EbtInt:
4499 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4500 break;
4501 case glslang::EbtUint:
4502 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4503 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004504 case glslang::EbtInt64:
4505 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4506 break;
4507 case glslang::EbtUint64:
4508 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4509 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004510 case glslang::EbtFloat:
4511 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4512 break;
4513 case glslang::EbtDouble:
4514 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4515 break;
4516 case glslang::EbtBool:
4517 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4518 break;
4519 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004520 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004521 break;
4522 }
4523 ++nextConst;
4524 }
4525 } else {
4526 // we have a non-aggregate (scalar) constant
4527 bool zero = nextConst >= consts.size();
4528 spv::Id scalar = 0;
4529 switch (glslangType.getBasicType()) {
4530 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004531 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004532 break;
4533 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004534 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004535 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004536 case glslang::EbtInt64:
4537 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4538 break;
4539 case glslang::EbtUint64:
4540 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4541 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004542 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004543 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004544 break;
4545 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004546 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004547 break;
4548 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004549 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004550 break;
4551 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004552 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004553 break;
4554 }
4555 ++nextConst;
4556 return scalar;
4557 }
4558
4559 return builder.makeCompositeConstant(typeId, spvConsts);
4560}
4561
John Kessenich7c1aa102015-10-15 13:29:11 -06004562// Return true if the node is a constant or symbol whose reading has no
4563// non-trivial observable cost or effect.
4564bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4565{
4566 // don't know what this is
4567 if (node == nullptr)
4568 return false;
4569
4570 // a constant is safe
4571 if (node->getAsConstantUnion() != nullptr)
4572 return true;
4573
4574 // not a symbol means non-trivial
4575 if (node->getAsSymbolNode() == nullptr)
4576 return false;
4577
4578 // a symbol, depends on what's being read
4579 switch (node->getType().getQualifier().storage) {
4580 case glslang::EvqTemporary:
4581 case glslang::EvqGlobal:
4582 case glslang::EvqIn:
4583 case glslang::EvqInOut:
4584 case glslang::EvqConst:
4585 case glslang::EvqConstReadOnly:
4586 case glslang::EvqUniform:
4587 return true;
4588 default:
4589 return false;
4590 }
qining25262b32016-05-06 17:25:16 -04004591}
John Kessenich7c1aa102015-10-15 13:29:11 -06004592
4593// A node is trivial if it is a single operation with no side effects.
4594// Error on the side of saying non-trivial.
4595// Return true if trivial.
4596bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4597{
4598 if (node == nullptr)
4599 return false;
4600
4601 // symbols and constants are trivial
4602 if (isTrivialLeaf(node))
4603 return true;
4604
4605 // otherwise, it needs to be a simple operation or one or two leaf nodes
4606
4607 // not a simple operation
4608 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4609 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4610 if (binaryNode == nullptr && unaryNode == nullptr)
4611 return false;
4612
4613 // not on leaf nodes
4614 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4615 return false;
4616
4617 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4618 return false;
4619 }
4620
4621 switch (node->getAsOperator()->getOp()) {
4622 case glslang::EOpLogicalNot:
4623 case glslang::EOpConvIntToBool:
4624 case glslang::EOpConvUintToBool:
4625 case glslang::EOpConvFloatToBool:
4626 case glslang::EOpConvDoubleToBool:
4627 case glslang::EOpEqual:
4628 case glslang::EOpNotEqual:
4629 case glslang::EOpLessThan:
4630 case glslang::EOpGreaterThan:
4631 case glslang::EOpLessThanEqual:
4632 case glslang::EOpGreaterThanEqual:
4633 case glslang::EOpIndexDirect:
4634 case glslang::EOpIndexDirectStruct:
4635 case glslang::EOpLogicalXor:
4636 case glslang::EOpAny:
4637 case glslang::EOpAll:
4638 return true;
4639 default:
4640 return false;
4641 }
4642}
4643
4644// Emit short-circuiting code, where 'right' is never evaluated unless
4645// the left side is true (for &&) or false (for ||).
4646spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4647{
4648 spv::Id boolTypeId = builder.makeBoolType();
4649
4650 // emit left operand
4651 builder.clearAccessChain();
4652 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004653 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004654
4655 // Operands to accumulate OpPhi operands
4656 std::vector<spv::Id> phiOperands;
4657 // accumulate left operand's phi information
4658 phiOperands.push_back(leftId);
4659 phiOperands.push_back(builder.getBuildPoint()->getId());
4660
4661 // Make the two kinds of operation symmetric with a "!"
4662 // || => emit "if (! left) result = right"
4663 // && => emit "if ( left) result = right"
4664 //
4665 // TODO: this runtime "not" for || could be avoided by adding functionality
4666 // to 'builder' to have an "else" without an "then"
4667 if (op == glslang::EOpLogicalOr)
4668 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4669
4670 // make an "if" based on the left value
4671 spv::Builder::If ifBuilder(leftId, builder);
4672
4673 // emit right operand as the "then" part of the "if"
4674 builder.clearAccessChain();
4675 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004676 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004677
4678 // accumulate left operand's phi information
4679 phiOperands.push_back(rightId);
4680 phiOperands.push_back(builder.getBuildPoint()->getId());
4681
4682 // finish the "if"
4683 ifBuilder.makeEndIf();
4684
4685 // phi together the two results
4686 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4687}
4688
Rex Xu9d93a232016-05-05 12:30:44 +08004689// Return type Id of the imported set of extended instructions corresponds to the name.
4690// Import this set if it has not been imported yet.
4691spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4692{
4693 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4694 return extBuiltinMap[name];
4695 else {
4696 builder.addExtensions(name);
4697 spv::Id extBuiltins = builder.import(name);
4698 extBuiltinMap[name] = extBuiltins;
4699 return extBuiltins;
4700 }
4701}
4702
John Kessenich140f3df2015-06-26 16:58:36 -06004703}; // end anonymous namespace
4704
4705namespace glslang {
4706
John Kessenich68d78fd2015-07-12 19:28:10 -06004707void GetSpirvVersion(std::string& version)
4708{
John Kessenich9e55f632015-07-15 10:03:39 -06004709 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004710 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004711 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004712 version = buf;
4713}
4714
John Kessenich140f3df2015-06-26 16:58:36 -06004715// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004716void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004717{
4718 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004719 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004720 for (int i = 0; i < (int)spirv.size(); ++i) {
4721 unsigned int word = spirv[i];
4722 out.write((const char*)&word, 4);
4723 }
4724 out.close();
4725}
4726
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004727// Write SPIR-V out to a text file with 32-bit hexadecimal words
4728void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4729{
4730 std::ofstream out;
4731 out.open(baseName, std::ios::binary | std::ios::out);
4732 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4733 const int WORDS_PER_LINE = 8;
4734 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4735 out << "\t";
4736 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4737 const unsigned int word = spirv[i + j];
4738 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4739 if (i + j + 1 < (int)spirv.size()) {
4740 out << ",";
4741 }
4742 }
4743 out << std::endl;
4744 }
4745 out.close();
4746}
4747
John Kessenich140f3df2015-06-26 16:58:36 -06004748//
4749// Set up the glslang traversal
4750//
4751void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4752{
Lei Zhang17535f72016-05-04 15:55:59 -04004753 spv::SpvBuildLogger logger;
4754 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004755}
4756
Lei Zhang17535f72016-05-04 15:55:59 -04004757void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004758{
John Kessenich140f3df2015-06-26 16:58:36 -06004759 TIntermNode* root = intermediate.getTreeRoot();
4760
4761 if (root == 0)
4762 return;
4763
4764 glslang::GetThreadPoolAllocator().push();
4765
Lei Zhang17535f72016-05-04 15:55:59 -04004766 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004767
4768 root->traverse(&it);
4769
4770 it.dumpSpv(spirv);
4771
4772 glslang::GetThreadPoolAllocator().pop();
4773}
4774
4775}; // end namespace glslang