blob: 6aec9e622721cf951f77db67a850737ef0aa81c4 [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
John Kessenichf6640762016-08-01 19:44:00 -0600286// Translate glslang precision to SPIR-V precision decorations.
287spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600288{
John Kessenichf6640762016-08-01 19:44:00 -0600289 switch (glslangPrecision) {
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
John Kessenichf6640762016-08-01 19:44:00 -0600297// Translate glslang type to SPIR-V precision decorations.
298spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
299{
300 return TranslatePrecisionDecoration(type.getQualifier().precision);
301}
302
John Kessenich140f3df2015-06-26 16:58:36 -0600303// Translate glslang type to SPIR-V block decorations.
304spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
305{
306 if (type.getBasicType() == glslang::EbtBlock) {
307 switch (type.getQualifier().storage) {
308 case glslang::EvqUniform: return spv::DecorationBlock;
309 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
310 case glslang::EvqVaryingIn: return spv::DecorationBlock;
311 case glslang::EvqVaryingOut: return spv::DecorationBlock;
312 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700313 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600314 break;
315 }
316 }
317
John Kessenich4016e382016-07-15 11:53:56 -0600318 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600319}
320
Rex Xu1da878f2016-02-21 20:59:01 +0800321// Translate glslang type to SPIR-V memory decorations.
322void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
323{
324 if (qualifier.coherent)
325 memory.push_back(spv::DecorationCoherent);
326 if (qualifier.volatil)
327 memory.push_back(spv::DecorationVolatile);
328 if (qualifier.restrict)
329 memory.push_back(spv::DecorationRestrict);
330 if (qualifier.readonly)
331 memory.push_back(spv::DecorationNonWritable);
332 if (qualifier.writeonly)
333 memory.push_back(spv::DecorationNonReadable);
334}
335
John Kessenich140f3df2015-06-26 16:58:36 -0600336// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700337spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600338{
339 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700340 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::ElmRowMajor:
342 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700343 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700345 default:
346 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600347 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600348 }
349 } else {
350 switch (type.getBasicType()) {
351 default:
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 break;
354 case glslang::EbtBlock:
355 switch (type.getQualifier().storage) {
356 case glslang::EvqUniform:
357 case glslang::EvqBuffer:
358 switch (type.getQualifier().layoutPacking) {
359 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 }
364 case glslang::EvqVaryingIn:
365 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700366 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600367 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600368 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700369 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600370 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 }
372 }
373 }
374}
375
376// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600377// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700378// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800379spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600380{
Rex Xubbceed72016-05-21 09:40:44 +0800381 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700382 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800384 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700385 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700386 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800388#ifdef AMD_EXTENSIONS
389 else if (qualifier.explicitInterp)
390 return spv::DecorationExplicitInterpAMD;
391#endif
Rex Xubbceed72016-05-21 09:40:44 +0800392 else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394}
395
396// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600397// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800398// should be applied.
399spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
400{
401 if (qualifier.patch)
402 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700403 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600404 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700405 else if (qualifier.sample) {
406 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600407 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700408 } else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410}
411
John Kessenich92187592016-02-01 13:45:25 -0700412// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700413spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600414{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationInvariant;
417 else
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600419}
420
qining9220dbb2016-05-04 17:34:38 -0400421// If glslang type is noContraction, return SPIR-V NoContraction decoration.
422spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
423{
424 if (qualifier.noContraction)
425 return spv::DecorationNoContraction;
426 else
John Kessenich4016e382016-07-15 11:53:56 -0600427 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400428}
429
David Netoa901ffe2016-06-08 14:11:40 +0100430// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
431// associated capabilities when required. For some built-in variables, a capability
432// is generated only when using the variable in an executable instruction, but not when
433// just declaring a struct member variable with it. This is true for PointSize,
434// ClipDistance, and CullDistance.
435spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600436{
437 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700438 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600439 // Defer adding the capability until the built-in is actually used.
440 if (! memberDeclaration) {
441 switch (glslangIntermediate->getStage()) {
442 case EShLangGeometry:
443 builder.addCapability(spv::CapabilityGeometryPointSize);
444 break;
445 case EShLangTessControl:
446 case EShLangTessEvaluation:
447 builder.addCapability(spv::CapabilityTessellationPointSize);
448 break;
449 default:
450 break;
451 }
John Kessenich92187592016-02-01 13:45:25 -0700452 }
453 return spv::BuiltInPointSize;
454
John Kessenichebb50532016-05-16 19:22:05 -0600455 // These *Distance capabilities logically belong here, but if the member is declared and
456 // then never used, consumers of SPIR-V prefer the capability not be declared.
457 // They are now generated when used, rather than here when declared.
458 // Potentially, the specification should be more clear what the minimum
459 // use needed is to trigger the capability.
460 //
John Kessenich92187592016-02-01 13:45:25 -0700461 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100462 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600463 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700464 return spv::BuiltInClipDistance;
465
466 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100467 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600468 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700469 return spv::BuiltInCullDistance;
470
471 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500472 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700473 return spv::BuiltInViewportIndex;
474
John Kessenich5e801132016-02-15 11:09:46 -0700475 case glslang::EbvSampleId:
476 builder.addCapability(spv::CapabilitySampleRateShading);
477 return spv::BuiltInSampleId;
478
479 case glslang::EbvSamplePosition:
480 builder.addCapability(spv::CapabilitySampleRateShading);
481 return spv::BuiltInSamplePosition;
482
483 case glslang::EbvSampleMask:
484 builder.addCapability(spv::CapabilitySampleRateShading);
485 return spv::BuiltInSampleMask;
486
John Kessenich78a45572016-07-08 14:05:15 -0600487 case glslang::EbvLayer:
488 builder.addCapability(spv::CapabilityGeometry);
489 return spv::BuiltInLayer;
490
John Kessenich140f3df2015-06-26 16:58:36 -0600491 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600492 case glslang::EbvVertexId: return spv::BuiltInVertexId;
493 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700494 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
495 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600496 case glslang::EbvBaseVertex:
497 case glslang::EbvBaseInstance:
498 case glslang::EbvDrawId:
499 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600500 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600501 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
503 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600504 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
505 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
506 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
507 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
508 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
509 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
510 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600511 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
512 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
513 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
514 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
515 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
516 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
517 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
518 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800519 case glslang::EbvSubGroupSize:
520 case glslang::EbvSubGroupInvocation:
521 case glslang::EbvSubGroupEqMask:
522 case glslang::EbvSubGroupGeMask:
523 case glslang::EbvSubGroupGtMask:
524 case glslang::EbvSubGroupLeMask:
525 case glslang::EbvSubGroupLtMask:
526 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600527 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600528 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800529#ifdef AMD_EXTENSIONS
530 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
531 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
532 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
533 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
534 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
535 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
536 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
537#endif
John Kessenich4016e382016-07-15 11:53:56 -0600538 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600539 }
540}
541
Rex Xufc618912015-09-09 16:42:49 +0800542// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700543spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800544{
545 assert(type.getBasicType() == glslang::EbtSampler);
546
John Kessenich5d0fa972016-02-15 11:57:00 -0700547 // Check for capabilities
548 switch (type.getQualifier().layoutFormat) {
549 case glslang::ElfRg32f:
550 case glslang::ElfRg16f:
551 case glslang::ElfR11fG11fB10f:
552 case glslang::ElfR16f:
553 case glslang::ElfRgba16:
554 case glslang::ElfRgb10A2:
555 case glslang::ElfRg16:
556 case glslang::ElfRg8:
557 case glslang::ElfR16:
558 case glslang::ElfR8:
559 case glslang::ElfRgba16Snorm:
560 case glslang::ElfRg16Snorm:
561 case glslang::ElfRg8Snorm:
562 case glslang::ElfR16Snorm:
563 case glslang::ElfR8Snorm:
564
565 case glslang::ElfRg32i:
566 case glslang::ElfRg16i:
567 case glslang::ElfRg8i:
568 case glslang::ElfR16i:
569 case glslang::ElfR8i:
570
571 case glslang::ElfRgb10a2ui:
572 case glslang::ElfRg32ui:
573 case glslang::ElfRg16ui:
574 case glslang::ElfRg8ui:
575 case glslang::ElfR16ui:
576 case glslang::ElfR8ui:
577 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
578 break;
579
580 default:
581 break;
582 }
583
584 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800585 switch (type.getQualifier().layoutFormat) {
586 case glslang::ElfNone: return spv::ImageFormatUnknown;
587 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
588 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
589 case glslang::ElfR32f: return spv::ImageFormatR32f;
590 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
591 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
592 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
593 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
594 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
595 case glslang::ElfR16f: return spv::ImageFormatR16f;
596 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
597 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
598 case glslang::ElfRg16: return spv::ImageFormatRg16;
599 case glslang::ElfRg8: return spv::ImageFormatRg8;
600 case glslang::ElfR16: return spv::ImageFormatR16;
601 case glslang::ElfR8: return spv::ImageFormatR8;
602 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
603 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
604 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
605 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
606 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
607 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
608 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
609 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
610 case glslang::ElfR32i: return spv::ImageFormatR32i;
611 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
612 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
613 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
614 case glslang::ElfR16i: return spv::ImageFormatR16i;
615 case glslang::ElfR8i: return spv::ImageFormatR8i;
616 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
617 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
618 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
619 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
620 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
621 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
622 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
623 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
624 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
625 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600626 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800627 }
628}
629
qining25262b32016-05-06 17:25:16 -0400630// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700631// descriptor set.
632bool IsDescriptorResource(const glslang::TType& type)
633{
John Kessenichf7497e22016-03-08 21:36:22 -0700634 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700635 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700636 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700637
638 // non block...
639 // basically samplerXXX/subpass/sampler/texture are all included
640 // if they are the global-scope-class, not the function parameter
641 // (or local, if they ever exist) class.
642 if (type.getBasicType() == glslang::EbtSampler)
643 return type.getQualifier().isUniformOrBuffer();
644
645 // None of the above.
646 return false;
647}
648
John Kesseniche0b6cad2015-12-24 10:30:13 -0700649void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
650{
651 if (child.layoutMatrix == glslang::ElmNone)
652 child.layoutMatrix = parent.layoutMatrix;
653
654 if (parent.invariant)
655 child.invariant = true;
656 if (parent.nopersp)
657 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800658#ifdef AMD_EXTENSIONS
659 if (parent.explicitInterp)
660 child.explicitInterp = true;
661#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700662 if (parent.flat)
663 child.flat = true;
664 if (parent.centroid)
665 child.centroid = true;
666 if (parent.patch)
667 child.patch = true;
668 if (parent.sample)
669 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800670 if (parent.coherent)
671 child.coherent = true;
672 if (parent.volatil)
673 child.volatil = true;
674 if (parent.restrict)
675 child.restrict = true;
676 if (parent.readonly)
677 child.readonly = true;
678 if (parent.writeonly)
679 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700680}
681
682bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
683{
John Kessenich7b9fa252016-01-21 18:56:57 -0700684 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700685 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600686 // - 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 -0700687 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600688 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700689}
690
John Kessenich140f3df2015-06-26 16:58:36 -0600691//
692// Implement the TGlslangToSpvTraverser class.
693//
694
Lei Zhang17535f72016-05-04 15:55:59 -0400695TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
696 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
697 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600698 inMain(false), mainTerminated(false), linkageOnly(false),
699 glslangIntermediate(glslangIntermediate)
700{
701 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
702
703 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700704 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600705 stdBuiltins = builder.import("GLSL.std.450");
706 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700707 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
708 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600709
710 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600711 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
712 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600713 builder.addSourceExtension(it->c_str());
714
715 // Add the top-level modes for this shader.
716
John Kessenich92187592016-02-01 13:45:25 -0700717 if (glslangIntermediate->getXfbMode()) {
718 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600719 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700720 }
John Kessenich140f3df2015-06-26 16:58:36 -0600721
722 unsigned int mode;
723 switch (glslangIntermediate->getStage()) {
724 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600725 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600726 break;
727
728 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600729 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600730 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
731 break;
732
733 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600734 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600735 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700736 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
737 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
738 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600739 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600740 }
John Kessenich4016e382016-07-15 11:53:56 -0600741 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600742 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
743
John Kesseniche6903322015-10-13 16:29:02 -0600744 switch (glslangIntermediate->getVertexSpacing()) {
745 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
746 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
747 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600749 }
John Kessenich4016e382016-07-15 11:53:56 -0600750 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600751 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
752
753 switch (glslangIntermediate->getVertexOrder()) {
754 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
755 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600756 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600757 }
John Kessenich4016e382016-07-15 11:53:56 -0600758 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600759 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
760
761 if (glslangIntermediate->getPointMode())
762 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600763 break;
764
765 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600766 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600767 switch (glslangIntermediate->getInputPrimitive()) {
768 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
769 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
770 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700771 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600772 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600773 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600774 }
John Kessenich4016e382016-07-15 11:53:56 -0600775 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600776 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600777
John Kessenich140f3df2015-06-26 16:58:36 -0600778 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
779
780 switch (glslangIntermediate->getOutputPrimitive()) {
781 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
782 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
783 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600784 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600785 }
John Kessenich4016e382016-07-15 11:53:56 -0600786 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600787 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
788 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
789 break;
790
791 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600792 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600793 if (glslangIntermediate->getPixelCenterInteger())
794 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600795
John Kessenich140f3df2015-06-26 16:58:36 -0600796 if (glslangIntermediate->getOriginUpperLeft())
797 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600798 else
799 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600800
801 if (glslangIntermediate->getEarlyFragmentTests())
802 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
803
804 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600805 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
806 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600807 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600808 }
John Kessenich4016e382016-07-15 11:53:56 -0600809 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600810 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
811
812 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
813 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600814 break;
815
816 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600817 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600818 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
819 glslangIntermediate->getLocalSize(1),
820 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600821 break;
822
823 default:
824 break;
825 }
826
827}
828
John Kessenich7ba63412015-12-20 17:37:07 -0700829// Finish everything and dump
830void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
831{
832 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100833 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
834 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700835
qiningda397332016-03-09 19:54:03 -0500836 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700837 builder.dump(out);
838}
839
John Kessenich140f3df2015-06-26 16:58:36 -0600840TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
841{
842 if (! mainTerminated) {
843 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
844 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600845 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600846 }
847}
848
849//
850// Implement the traversal functions.
851//
852// Return true from interior nodes to have the external traversal
853// continue on to children. Return false if children were
854// already processed.
855//
856
857//
qining25262b32016-05-06 17:25:16 -0400858// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600859// - uniform/input reads
860// - output writes
861// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
862// - something simple that degenerates into the last bullet
863//
864void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
865{
qining75d1d802016-04-06 14:42:01 -0400866 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
867 if (symbol->getType().getQualifier().isSpecConstant())
868 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
869
John Kessenich140f3df2015-06-26 16:58:36 -0600870 // getSymbolId() will set up all the IO decorations on the first call.
871 // Formal function parameters were mapped during makeFunctions().
872 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700873
874 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
875 if (builder.isPointer(id)) {
876 spv::StorageClass sc = builder.getStorageClass(id);
877 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
878 iOSet.insert(id);
879 }
880
881 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700882 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600883 // Prepare to generate code for the access
884
885 // L-value chains will be computed left to right. We're on the symbol now,
886 // which is the left-most part of the access chain, so now is "clear" time,
887 // followed by setting the base.
888 builder.clearAccessChain();
889
890 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700891 // except for
892 // A) "const in" arguments to a function, which are an intermediate object.
893 // See comments in handleUserFunctionCall().
894 // B) Specialization constants (normal constant don't even come in as a variable),
895 // These are also pure R-values.
896 glslang::TQualifier qualifier = symbol->getQualifier();
897 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
898 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600899 builder.setAccessChainRValue(id);
900 else
901 builder.setAccessChainLValue(id);
902 }
903}
904
905bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
906{
qining40887662016-04-03 22:20:42 -0400907 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
908 if (node->getType().getQualifier().isSpecConstant())
909 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
910
John Kessenich140f3df2015-06-26 16:58:36 -0600911 // First, handle special cases
912 switch (node->getOp()) {
913 case glslang::EOpAssign:
914 case glslang::EOpAddAssign:
915 case glslang::EOpSubAssign:
916 case glslang::EOpMulAssign:
917 case glslang::EOpVectorTimesMatrixAssign:
918 case glslang::EOpVectorTimesScalarAssign:
919 case glslang::EOpMatrixTimesScalarAssign:
920 case glslang::EOpMatrixTimesMatrixAssign:
921 case glslang::EOpDivAssign:
922 case glslang::EOpModAssign:
923 case glslang::EOpAndAssign:
924 case glslang::EOpInclusiveOrAssign:
925 case glslang::EOpExclusiveOrAssign:
926 case glslang::EOpLeftShiftAssign:
927 case glslang::EOpRightShiftAssign:
928 // A bin-op assign "a += b" means the same thing as "a = a + b"
929 // where a is evaluated before b. For a simple assignment, GLSL
930 // says to evaluate the left before the right. So, always, left
931 // node then right node.
932 {
933 // get the left l-value, save it away
934 builder.clearAccessChain();
935 node->getLeft()->traverse(this);
936 spv::Builder::AccessChain lValue = builder.getAccessChain();
937
938 // evaluate the right
939 builder.clearAccessChain();
940 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700941 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600942
943 if (node->getOp() != glslang::EOpAssign) {
944 // the left is also an r-value
945 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700946 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600947
948 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600949 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400950 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600951 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
952 node->getType().getBasicType());
953
954 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700955 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600956 }
957
958 // store the result
959 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800960 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600961
962 // assignments are expressions having an rValue after they are evaluated...
963 builder.clearAccessChain();
964 builder.setAccessChainRValue(rValue);
965 }
966 return false;
967 case glslang::EOpIndexDirect:
968 case glslang::EOpIndexDirectStruct:
969 {
970 // Get the left part of the access chain.
971 node->getLeft()->traverse(this);
972
973 // Add the next element in the chain
974
David Netoa901ffe2016-06-08 14:11:40 +0100975 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600976 if (! node->getLeft()->getType().isArray() &&
977 node->getLeft()->getType().isVector() &&
978 node->getOp() == glslang::EOpIndexDirect) {
979 // This is essentially a hard-coded vector swizzle of size 1,
980 // so short circuit the access-chain stuff with a swizzle.
981 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100982 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600983 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600984 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100985 int spvIndex = glslangIndex;
986 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
987 node->getOp() == glslang::EOpIndexDirectStruct)
988 {
989 // This may be, e.g., an anonymous block-member selection, which generally need
990 // index remapping due to hidden members in anonymous blocks.
991 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
992 assert(remapper.size() > 0);
993 spvIndex = remapper[glslangIndex];
994 }
John Kessenichebb50532016-05-16 19:22:05 -0600995
David Netoa901ffe2016-06-08 14:11:40 +0100996 // normal case for indexing array or structure or block
997 builder.accessChainPush(builder.makeIntConstant(spvIndex));
998
999 // Add capabilities here for accessing PointSize and clip/cull distance.
1000 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001001 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001002 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 }
1004 }
1005 return false;
1006 case glslang::EOpIndexIndirect:
1007 {
1008 // Structure or array or vector indirection.
1009 // Will use native SPIR-V access-chain for struct and array indirection;
1010 // matrices are arrays of vectors, so will also work for a matrix.
1011 // Will use the access chain's 'component' for variable index into a vector.
1012
1013 // This adapter is building access chains left to right.
1014 // Set up the access chain to the left.
1015 node->getLeft()->traverse(this);
1016
1017 // save it so that computing the right side doesn't trash it
1018 spv::Builder::AccessChain partial = builder.getAccessChain();
1019
1020 // compute the next index in the chain
1021 builder.clearAccessChain();
1022 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001023 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001024
1025 // restore the saved access chain
1026 builder.setAccessChain(partial);
1027
1028 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001029 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001030 else
John Kessenichfa668da2015-09-13 14:46:30 -06001031 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001032 }
1033 return false;
1034 case glslang::EOpVectorSwizzle:
1035 {
1036 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001037 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001038 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001039 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001040 }
1041 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001042 case glslang::EOpLogicalOr:
1043 case glslang::EOpLogicalAnd:
1044 {
1045
1046 // These may require short circuiting, but can sometimes be done as straight
1047 // binary operations. The right operand must be short circuited if it has
1048 // side effects, and should probably be if it is complex.
1049 if (isTrivial(node->getRight()->getAsTyped()))
1050 break; // handle below as a normal binary operation
1051 // otherwise, we need to do dynamic short circuiting on the right operand
1052 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1053 builder.clearAccessChain();
1054 builder.setAccessChainRValue(result);
1055 }
1056 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001057 default:
1058 break;
1059 }
1060
1061 // Assume generic binary op...
1062
John Kessenich32cfd492016-02-02 12:37:46 -07001063 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.clearAccessChain();
1065 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001066 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001067
John Kessenich32cfd492016-02-02 12:37:46 -07001068 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001069 builder.clearAccessChain();
1070 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001071 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001072
John Kessenich32cfd492016-02-02 12:37:46 -07001073 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001074 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001075 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001076 convertGlslangToSpvType(node->getType()), left, right,
1077 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001078
John Kessenich50e57562015-12-21 21:21:11 -07001079 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001080 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001081 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001082 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001083 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001084 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001085 return false;
1086 }
John Kessenich140f3df2015-06-26 16:58:36 -06001087}
1088
1089bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1090{
qining40887662016-04-03 22:20:42 -04001091 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1092 if (node->getType().getQualifier().isSpecConstant())
1093 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1094
John Kessenichfc51d282015-08-19 13:34:18 -06001095 spv::Id result = spv::NoResult;
1096
1097 // try texturing first
1098 result = createImageTextureFunctionCall(node);
1099 if (result != spv::NoResult) {
1100 builder.clearAccessChain();
1101 builder.setAccessChainRValue(result);
1102
1103 return false; // done with this node
1104 }
1105
1106 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001107
1108 if (node->getOp() == glslang::EOpArrayLength) {
1109 // Quite special; won't want to evaluate the operand.
1110
1111 // Normal .length() would have been constant folded by the front-end.
1112 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001113 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001114 assert(node->getOperand()->getType().isRuntimeSizedArray());
1115 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1116 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001117 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1118 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001119
1120 builder.clearAccessChain();
1121 builder.setAccessChainRValue(length);
1122
1123 return false;
1124 }
1125
John Kessenichfc51d282015-08-19 13:34:18 -06001126 // Start by evaluating the operand
1127
John Kessenich8c8505c2016-07-26 12:50:38 -06001128 // Does it need a swizzle inversion? If so, evaluation is inverted;
1129 // operate first on the swizzle base, then apply the swizzle.
1130 spv::Id invertedType = spv::NoType;
1131 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1132 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1133 invertedType = getInvertedSwizzleType(*node->getOperand());
1134
John Kessenich140f3df2015-06-26 16:58:36 -06001135 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001136 if (invertedType != spv::NoType)
1137 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1138 else
1139 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001140
Rex Xufc618912015-09-09 16:42:49 +08001141 spv::Id operand = spv::NoResult;
1142
1143 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1144 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001145 node->getOp() == glslang::EOpAtomicCounter ||
1146 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001147 operand = builder.accessChainGetLValue(); // Special case l-value operands
1148 else
John Kessenich32cfd492016-02-02 12:37:46 -07001149 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001150
John Kessenichf6640762016-08-01 19:44:00 -06001151 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001152 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001153
1154 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001155 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001156 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001157
1158 // if not, then possibly an operation
1159 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001160 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001161
1162 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001163 if (invertedType)
1164 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1165
John Kessenich140f3df2015-06-26 16:58:36 -06001166 builder.clearAccessChain();
1167 builder.setAccessChainRValue(result);
1168
1169 return false; // done with this node
1170 }
1171
1172 // it must be a special case, check...
1173 switch (node->getOp()) {
1174 case glslang::EOpPostIncrement:
1175 case glslang::EOpPostDecrement:
1176 case glslang::EOpPreIncrement:
1177 case glslang::EOpPreDecrement:
1178 {
1179 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001180 spv::Id one = 0;
1181 if (node->getBasicType() == glslang::EbtFloat)
1182 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001183 else if (node->getBasicType() == glslang::EbtDouble)
1184 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001185 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1186 one = builder.makeInt64Constant(1);
1187 else
1188 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001189 glslang::TOperator op;
1190 if (node->getOp() == glslang::EOpPreIncrement ||
1191 node->getOp() == glslang::EOpPostIncrement)
1192 op = glslang::EOpAdd;
1193 else
1194 op = glslang::EOpSub;
1195
John Kessenichf6640762016-08-01 19:44:00 -06001196 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001197 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001198 convertGlslangToSpvType(node->getType()), operand, one,
1199 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001200 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001201
1202 // The result of operation is always stored, but conditionally the
1203 // consumed result. The consumed result is always an r-value.
1204 builder.accessChainStore(result);
1205 builder.clearAccessChain();
1206 if (node->getOp() == glslang::EOpPreIncrement ||
1207 node->getOp() == glslang::EOpPreDecrement)
1208 builder.setAccessChainRValue(result);
1209 else
1210 builder.setAccessChainRValue(operand);
1211 }
1212
1213 return false;
1214
1215 case glslang::EOpEmitStreamVertex:
1216 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1217 return false;
1218 case glslang::EOpEndStreamPrimitive:
1219 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1220 return false;
1221
1222 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001223 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001224 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001225 }
John Kessenich140f3df2015-06-26 16:58:36 -06001226}
1227
1228bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1229{
qining27e04a02016-04-14 16:40:20 -04001230 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1231 if (node->getType().getQualifier().isSpecConstant())
1232 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1233
John Kessenichfc51d282015-08-19 13:34:18 -06001234 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1236 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001237
1238 // try texturing
1239 result = createImageTextureFunctionCall(node);
1240 if (result != spv::NoResult) {
1241 builder.clearAccessChain();
1242 builder.setAccessChainRValue(result);
1243
1244 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001245 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001246 // "imageStore" is a special case, which has no result
1247 return false;
1248 }
John Kessenichfc51d282015-08-19 13:34:18 -06001249
John Kessenich140f3df2015-06-26 16:58:36 -06001250 glslang::TOperator binOp = glslang::EOpNull;
1251 bool reduceComparison = true;
1252 bool isMatrix = false;
1253 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001254 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001255
1256 assert(node->getOp());
1257
John Kessenichf6640762016-08-01 19:44:00 -06001258 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001259
1260 switch (node->getOp()) {
1261 case glslang::EOpSequence:
1262 {
1263 if (preVisit)
1264 ++sequenceDepth;
1265 else
1266 --sequenceDepth;
1267
1268 if (sequenceDepth == 1) {
1269 // If this is the parent node of all the functions, we want to see them
1270 // early, so all call points have actual SPIR-V functions to reference.
1271 // In all cases, still let the traverser visit the children for us.
1272 makeFunctions(node->getAsAggregate()->getSequence());
1273
1274 // Also, we want all globals initializers to go into the entry of main(), before
1275 // anything else gets there, so visit out of order, doing them all now.
1276 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1277
1278 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1279 // so do them manually.
1280 visitFunctions(node->getAsAggregate()->getSequence());
1281
1282 return false;
1283 }
1284
1285 return true;
1286 }
1287 case glslang::EOpLinkerObjects:
1288 {
1289 if (visit == glslang::EvPreVisit)
1290 linkageOnly = true;
1291 else
1292 linkageOnly = false;
1293
1294 return true;
1295 }
1296 case glslang::EOpComma:
1297 {
1298 // processing from left to right naturally leaves the right-most
1299 // lying around in the access chain
1300 glslang::TIntermSequence& glslangOperands = node->getSequence();
1301 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1302 glslangOperands[i]->traverse(this);
1303
1304 return false;
1305 }
1306 case glslang::EOpFunction:
1307 if (visit == glslang::EvPreVisit) {
1308 if (isShaderEntrypoint(node)) {
1309 inMain = true;
1310 builder.setBuildPoint(shaderEntry->getLastBlock());
1311 } else {
1312 handleFunctionEntry(node);
1313 }
1314 } else {
1315 if (inMain)
1316 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001317 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001318 inMain = false;
1319 }
1320
1321 return true;
1322 case glslang::EOpParameters:
1323 // Parameters will have been consumed by EOpFunction processing, but not
1324 // the body, so we still visited the function node's children, making this
1325 // child redundant.
1326 return false;
1327 case glslang::EOpFunctionCall:
1328 {
1329 if (node->isUserDefined())
1330 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001331 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1332 if (result) {
1333 builder.clearAccessChain();
1334 builder.setAccessChainRValue(result);
1335 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001336 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 return false;
1339 }
1340 case glslang::EOpConstructMat2x2:
1341 case glslang::EOpConstructMat2x3:
1342 case glslang::EOpConstructMat2x4:
1343 case glslang::EOpConstructMat3x2:
1344 case glslang::EOpConstructMat3x3:
1345 case glslang::EOpConstructMat3x4:
1346 case glslang::EOpConstructMat4x2:
1347 case glslang::EOpConstructMat4x3:
1348 case glslang::EOpConstructMat4x4:
1349 case glslang::EOpConstructDMat2x2:
1350 case glslang::EOpConstructDMat2x3:
1351 case glslang::EOpConstructDMat2x4:
1352 case glslang::EOpConstructDMat3x2:
1353 case glslang::EOpConstructDMat3x3:
1354 case glslang::EOpConstructDMat3x4:
1355 case glslang::EOpConstructDMat4x2:
1356 case glslang::EOpConstructDMat4x3:
1357 case glslang::EOpConstructDMat4x4:
1358 isMatrix = true;
1359 // fall through
1360 case glslang::EOpConstructFloat:
1361 case glslang::EOpConstructVec2:
1362 case glslang::EOpConstructVec3:
1363 case glslang::EOpConstructVec4:
1364 case glslang::EOpConstructDouble:
1365 case glslang::EOpConstructDVec2:
1366 case glslang::EOpConstructDVec3:
1367 case glslang::EOpConstructDVec4:
1368 case glslang::EOpConstructBool:
1369 case glslang::EOpConstructBVec2:
1370 case glslang::EOpConstructBVec3:
1371 case glslang::EOpConstructBVec4:
1372 case glslang::EOpConstructInt:
1373 case glslang::EOpConstructIVec2:
1374 case glslang::EOpConstructIVec3:
1375 case glslang::EOpConstructIVec4:
1376 case glslang::EOpConstructUint:
1377 case glslang::EOpConstructUVec2:
1378 case glslang::EOpConstructUVec3:
1379 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001380 case glslang::EOpConstructInt64:
1381 case glslang::EOpConstructI64Vec2:
1382 case glslang::EOpConstructI64Vec3:
1383 case glslang::EOpConstructI64Vec4:
1384 case glslang::EOpConstructUint64:
1385 case glslang::EOpConstructU64Vec2:
1386 case glslang::EOpConstructU64Vec3:
1387 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001388 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001389 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001390 {
1391 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001392 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001393 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001394 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001395 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001396 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001397 std::vector<spv::Id> constituents;
1398 for (int c = 0; c < (int)arguments.size(); ++c)
1399 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001400 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001401 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001402 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001403 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001404 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001405
1406 builder.clearAccessChain();
1407 builder.setAccessChainRValue(constructed);
1408
1409 return false;
1410 }
1411
1412 // These six are component-wise compares with component-wise results.
1413 // Forward on to createBinaryOperation(), requesting a vector result.
1414 case glslang::EOpLessThan:
1415 case glslang::EOpGreaterThan:
1416 case glslang::EOpLessThanEqual:
1417 case glslang::EOpGreaterThanEqual:
1418 case glslang::EOpVectorEqual:
1419 case glslang::EOpVectorNotEqual:
1420 {
1421 // Map the operation to a binary
1422 binOp = node->getOp();
1423 reduceComparison = false;
1424 switch (node->getOp()) {
1425 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1426 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1427 default: binOp = node->getOp(); break;
1428 }
1429
1430 break;
1431 }
1432 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001433 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001434 binOp = glslang::EOpMul;
1435 break;
1436 case glslang::EOpOuterProduct:
1437 // two vectors multiplied to make a matrix
1438 binOp = glslang::EOpOuterProduct;
1439 break;
1440 case glslang::EOpDot:
1441 {
qining25262b32016-05-06 17:25:16 -04001442 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001443 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001444 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001445 binOp = glslang::EOpMul;
1446 break;
1447 }
1448 case glslang::EOpMod:
1449 // when an aggregate, this is the floating-point mod built-in function,
1450 // which can be emitted by the one in createBinaryOperation()
1451 binOp = glslang::EOpMod;
1452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001453 case glslang::EOpEmitVertex:
1454 case glslang::EOpEndPrimitive:
1455 case glslang::EOpBarrier:
1456 case glslang::EOpMemoryBarrier:
1457 case glslang::EOpMemoryBarrierAtomicCounter:
1458 case glslang::EOpMemoryBarrierBuffer:
1459 case glslang::EOpMemoryBarrierImage:
1460 case glslang::EOpMemoryBarrierShared:
1461 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001462 case glslang::EOpAllMemoryBarrierWithGroupSync:
1463 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1464 case glslang::EOpWorkgroupMemoryBarrier:
1465 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001466 noReturnValue = true;
1467 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1468 break;
1469
John Kessenich426394d2015-07-23 10:22:48 -06001470 case glslang::EOpAtomicAdd:
1471 case glslang::EOpAtomicMin:
1472 case glslang::EOpAtomicMax:
1473 case glslang::EOpAtomicAnd:
1474 case glslang::EOpAtomicOr:
1475 case glslang::EOpAtomicXor:
1476 case glslang::EOpAtomicExchange:
1477 case glslang::EOpAtomicCompSwap:
1478 atomic = true;
1479 break;
1480
John Kessenich140f3df2015-06-26 16:58:36 -06001481 default:
1482 break;
1483 }
1484
1485 //
1486 // See if it maps to a regular operation.
1487 //
John Kessenich140f3df2015-06-26 16:58:36 -06001488 if (binOp != glslang::EOpNull) {
1489 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1490 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1491 assert(left && right);
1492
1493 builder.clearAccessChain();
1494 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001495 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001496
1497 builder.clearAccessChain();
1498 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001499 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001500
qining25262b32016-05-06 17:25:16 -04001501 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001502 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001503 left->getType().getBasicType(), reduceComparison);
1504
1505 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001506 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001507 builder.clearAccessChain();
1508 builder.setAccessChainRValue(result);
1509
1510 return false;
1511 }
1512
John Kessenich426394d2015-07-23 10:22:48 -06001513 //
1514 // Create the list of operands.
1515 //
John Kessenich140f3df2015-06-26 16:58:36 -06001516 glslang::TIntermSequence& glslangOperands = node->getSequence();
1517 std::vector<spv::Id> operands;
1518 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001519 // special case l-value operands; there are just a few
1520 bool lvalue = false;
1521 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001522 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001523 case glslang::EOpModf:
1524 if (arg == 1)
1525 lvalue = true;
1526 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001527 case glslang::EOpInterpolateAtSample:
1528 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001529#ifdef AMD_EXTENSIONS
1530 case glslang::EOpInterpolateAtVertex:
1531#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001532 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001533 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001534
1535 // Does it need a swizzle inversion? If so, evaluation is inverted;
1536 // operate first on the swizzle base, then apply the swizzle.
1537 if (glslangOperands[0]->getAsOperator() &&
1538 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1539 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1540 }
Rex Xu7a26c172015-12-08 17:12:09 +08001541 break;
Rex Xud4782c12015-09-06 16:30:11 +08001542 case glslang::EOpAtomicAdd:
1543 case glslang::EOpAtomicMin:
1544 case glslang::EOpAtomicMax:
1545 case glslang::EOpAtomicAnd:
1546 case glslang::EOpAtomicOr:
1547 case glslang::EOpAtomicXor:
1548 case glslang::EOpAtomicExchange:
1549 case glslang::EOpAtomicCompSwap:
1550 if (arg == 0)
1551 lvalue = true;
1552 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001553 case glslang::EOpAddCarry:
1554 case glslang::EOpSubBorrow:
1555 if (arg == 2)
1556 lvalue = true;
1557 break;
1558 case glslang::EOpUMulExtended:
1559 case glslang::EOpIMulExtended:
1560 if (arg >= 2)
1561 lvalue = true;
1562 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001563 default:
1564 break;
1565 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001566 builder.clearAccessChain();
1567 if (invertedType != spv::NoType && arg == 0)
1568 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1569 else
1570 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001571 if (lvalue)
1572 operands.push_back(builder.accessChainGetLValue());
1573 else
John Kessenich32cfd492016-02-02 12:37:46 -07001574 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001575 }
John Kessenich426394d2015-07-23 10:22:48 -06001576
1577 if (atomic) {
1578 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001579 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001580 } else {
1581 // Pass through to generic operations.
1582 switch (glslangOperands.size()) {
1583 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001584 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001585 break;
1586 case 1:
qining25262b32016-05-06 17:25:16 -04001587 result = createUnaryOperation(
1588 node->getOp(), precision,
1589 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001590 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001591 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001592 break;
1593 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001594 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001595 break;
1596 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001597 if (invertedType)
1598 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001599 }
1600
1601 if (noReturnValue)
1602 return false;
1603
1604 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001605 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001606 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001607 } else {
1608 builder.clearAccessChain();
1609 builder.setAccessChainRValue(result);
1610 return false;
1611 }
1612}
1613
1614bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1615{
1616 // This path handles both if-then-else and ?:
1617 // The if-then-else has a node type of void, while
1618 // ?: has a non-void node type
1619 spv::Id result = 0;
1620 if (node->getBasicType() != glslang::EbtVoid) {
1621 // don't handle this as just on-the-fly temporaries, because there will be two names
1622 // and better to leave SSA to later passes
1623 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1624 }
1625
1626 // emit the condition before doing anything with selection
1627 node->getCondition()->traverse(this);
1628
1629 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001630 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001631
1632 if (node->getTrueBlock()) {
1633 // emit the "then" statement
1634 node->getTrueBlock()->traverse(this);
1635 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001636 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001637 }
1638
1639 if (node->getFalseBlock()) {
1640 ifBuilder.makeBeginElse();
1641 // emit the "else" statement
1642 node->getFalseBlock()->traverse(this);
1643 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001644 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001645 }
1646
1647 ifBuilder.makeEndIf();
1648
1649 if (result) {
1650 // GLSL only has r-values as the result of a :?, but
1651 // if we have an l-value, that can be more efficient if it will
1652 // become the base of a complex r-value expression, because the
1653 // next layer copies r-values into memory to use the access-chain mechanism
1654 builder.clearAccessChain();
1655 builder.setAccessChainLValue(result);
1656 }
1657
1658 return false;
1659}
1660
1661bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1662{
1663 // emit and get the condition before doing anything with switch
1664 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001665 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001666
1667 // browse the children to sort out code segments
1668 int defaultSegment = -1;
1669 std::vector<TIntermNode*> codeSegments;
1670 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1671 std::vector<int> caseValues;
1672 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1673 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1674 TIntermNode* child = *c;
1675 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001676 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001677 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001678 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001679 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1680 } else
1681 codeSegments.push_back(child);
1682 }
1683
qining25262b32016-05-06 17:25:16 -04001684 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001685 // statements between the last case and the end of the switch statement
1686 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1687 (int)codeSegments.size() == defaultSegment)
1688 codeSegments.push_back(nullptr);
1689
1690 // make the switch statement
1691 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001692 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001693
1694 // emit all the code in the segments
1695 breakForLoop.push(false);
1696 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1697 builder.nextSwitchSegment(segmentBlocks, s);
1698 if (codeSegments[s])
1699 codeSegments[s]->traverse(this);
1700 else
1701 builder.addSwitchBreak();
1702 }
1703 breakForLoop.pop();
1704
1705 builder.endSwitch(segmentBlocks);
1706
1707 return false;
1708}
1709
1710void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1711{
1712 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001713 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001714
1715 builder.clearAccessChain();
1716 builder.setAccessChainRValue(constant);
1717}
1718
1719bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1720{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001721 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001722 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001723 // Spec requires back edges to target header blocks, and every header block
1724 // must dominate its merge block. Make a header block first to ensure these
1725 // conditions are met. By definition, it will contain OpLoopMerge, followed
1726 // by a block-ending branch. But we don't want to put any other body/test
1727 // instructions in it, since the body/test may have arbitrary instructions,
1728 // including merges of its own.
1729 builder.setBuildPoint(&blocks.head);
1730 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001731 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001732 spv::Block& test = builder.makeNewBlock();
1733 builder.createBranch(&test);
1734
1735 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001736 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001737 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001738 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001739 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1740
1741 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001742 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001743 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001744 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001745 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001746 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001747
1748 builder.setBuildPoint(&blocks.continue_target);
1749 if (node->getTerminal())
1750 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001751 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001752 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001753 builder.createBranch(&blocks.body);
1754
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001755 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001756 builder.setBuildPoint(&blocks.body);
1757 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001758 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001759 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001760 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001761
1762 builder.setBuildPoint(&blocks.continue_target);
1763 if (node->getTerminal())
1764 node->getTerminal()->traverse(this);
1765 if (node->getTest()) {
1766 node->getTest()->traverse(this);
1767 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001768 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001769 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001770 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001771 // TODO: unless there was a break/return/discard instruction
1772 // somewhere in the body, this is an infinite loop, so we should
1773 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001774 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001775 }
John Kessenich140f3df2015-06-26 16:58:36 -06001776 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001777 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001778 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001779 return false;
1780}
1781
1782bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1783{
1784 if (node->getExpression())
1785 node->getExpression()->traverse(this);
1786
1787 switch (node->getFlowOp()) {
1788 case glslang::EOpKill:
1789 builder.makeDiscard();
1790 break;
1791 case glslang::EOpBreak:
1792 if (breakForLoop.top())
1793 builder.createLoopExit();
1794 else
1795 builder.addSwitchBreak();
1796 break;
1797 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001798 builder.createLoopContinue();
1799 break;
1800 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001801 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001802 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001803 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001804 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001805
1806 builder.clearAccessChain();
1807 break;
1808
1809 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001810 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001811 break;
1812 }
1813
1814 return false;
1815}
1816
1817spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1818{
qining25262b32016-05-06 17:25:16 -04001819 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001820 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001821 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001822 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001823 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001824 }
1825
1826 // Now, handle actual variables
1827 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1828 spv::Id spvType = convertGlslangToSpvType(node->getType());
1829
1830 const char* name = node->getName().c_str();
1831 if (glslang::IsAnonymous(name))
1832 name = "";
1833
1834 return builder.createVariable(storageClass, spvType, name);
1835}
1836
1837// Return type Id of the sampled type.
1838spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1839{
1840 switch (sampler.type) {
1841 case glslang::EbtFloat: return builder.makeFloatType(32);
1842 case glslang::EbtInt: return builder.makeIntType(32);
1843 case glslang::EbtUint: return builder.makeUintType(32);
1844 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001845 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 return builder.makeFloatType(32);
1847 }
1848}
1849
John Kessenich8c8505c2016-07-26 12:50:38 -06001850// If node is a swizzle operation, return the type that should be used if
1851// the swizzle base is first consumed by another operation, before the swizzle
1852// is applied.
1853spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1854{
1855 if (node.getAsOperator() &&
1856 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1857 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1858 else
1859 return spv::NoType;
1860}
1861
1862// When inverting a swizzle with a parent op, this function
1863// will apply the swizzle operation to a completed parent operation.
1864spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1865{
1866 std::vector<unsigned> swizzle;
1867 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1868 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1869}
1870
1871
1872// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1873void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1874{
1875 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1876 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1877 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1878}
1879
John Kessenich3ac051e2015-12-20 11:29:16 -07001880// Convert from a glslang type to an SPV type, by calling into a
1881// recursive version of this function. This establishes the inherited
1882// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001883spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1884{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001885 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001886}
1887
1888// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001889// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001890// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001892{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001894
1895 switch (type.getBasicType()) {
1896 case glslang::EbtVoid:
1897 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001898 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001899 break;
1900 case glslang::EbtFloat:
1901 spvType = builder.makeFloatType(32);
1902 break;
1903 case glslang::EbtDouble:
1904 spvType = builder.makeFloatType(64);
1905 break;
1906 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001907 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1908 // a 32-bit int where non-0 means true.
1909 if (explicitLayout != glslang::ElpNone)
1910 spvType = builder.makeUintType(32);
1911 else
1912 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001913 break;
1914 case glslang::EbtInt:
1915 spvType = builder.makeIntType(32);
1916 break;
1917 case glslang::EbtUint:
1918 spvType = builder.makeUintType(32);
1919 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001920 case glslang::EbtInt64:
1921 builder.addCapability(spv::CapabilityInt64);
1922 spvType = builder.makeIntType(64);
1923 break;
1924 case glslang::EbtUint64:
1925 builder.addCapability(spv::CapabilityInt64);
1926 spvType = builder.makeUintType(64);
1927 break;
John Kessenich426394d2015-07-23 10:22:48 -06001928 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001929 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001930 spvType = builder.makeUintType(32);
1931 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001932 case glslang::EbtSampler:
1933 {
1934 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001935 if (sampler.sampler) {
1936 // pure sampler
1937 spvType = builder.makeSamplerType();
1938 } else {
1939 // an image is present, make its type
1940 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1941 sampler.image ? 2 : 1, TranslateImageFormat(type));
1942 if (sampler.combined) {
1943 // already has both image and sampler, make the combined type
1944 spvType = builder.makeSampledImageType(spvType);
1945 }
John Kessenich55e7d112015-11-15 21:33:39 -07001946 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001947 }
John Kessenich140f3df2015-06-26 16:58:36 -06001948 break;
1949 case glslang::EbtStruct:
1950 case glslang::EbtBlock:
1951 {
1952 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001953 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001954
1955 // Try to share structs for different layouts, but not yet for other
1956 // kinds of qualification (primarily not yet including interpolant qualification).
1957 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001958 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001959 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001960 break;
1961
1962 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001963 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001964 memberRemapper[glslangMembers].resize(glslangMembers->size());
1965 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001966 }
1967 break;
1968 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001969 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 break;
1971 }
1972
1973 if (type.isMatrix())
1974 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1975 else {
1976 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1977 if (type.getVectorSize() > 1)
1978 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1979 }
1980
1981 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001982 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1983
John Kessenichc9a80832015-09-12 12:17:44 -06001984 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001985 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001986 // We need to decorate array strides for types needing explicit layout, except blocks.
1987 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001988 // Use a dummy glslang type for querying internal strides of
1989 // arrays of arrays, but using just a one-dimensional array.
1990 glslang::TType simpleArrayType(type, 0); // deference type of the array
1991 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1992 simpleArrayType.getArraySizes().dereference();
1993
1994 // Will compute the higher-order strides here, rather than making a whole
1995 // pile of types and doing repetitive recursion on their contents.
1996 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1997 }
John Kessenichf8842e52016-01-04 19:22:56 -07001998
1999 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002000 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002001 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002002 if (stride > 0)
2003 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002004 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002005 }
2006 } else {
2007 // single-dimensional array, and don't yet have stride
2008
John Kessenichf8842e52016-01-04 19:22:56 -07002009 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002010 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2011 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002012 }
John Kessenich31ed4832015-09-09 17:51:38 -06002013
John Kessenichc9a80832015-09-12 12:17:44 -06002014 // Do the outer dimension, which might not be known for a runtime-sized array
2015 if (type.isRuntimeSizedArray()) {
2016 spvType = builder.makeRuntimeArray(spvType);
2017 } else {
2018 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002019 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002020 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002021 if (stride > 0)
2022 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002023 }
2024
2025 return spvType;
2026}
2027
John Kessenich6090df02016-06-30 21:18:02 -06002028
2029// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2030// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2031// Mutually recursive with convertGlslangToSpvType().
2032spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2033 const glslang::TTypeList* glslangMembers,
2034 glslang::TLayoutPacking explicitLayout,
2035 const glslang::TQualifier& qualifier)
2036{
2037 // Create a vector of struct types for SPIR-V to consume
2038 std::vector<spv::Id> spvMembers;
2039 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2040 int locationOffset = 0; // for use across struct members, when they are called recursively
2041 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2042 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2043 if (glslangMember.hiddenMember()) {
2044 ++memberDelta;
2045 if (type.getBasicType() == glslang::EbtBlock)
2046 memberRemapper[glslangMembers][i] = -1;
2047 } else {
2048 if (type.getBasicType() == glslang::EbtBlock)
2049 memberRemapper[glslangMembers][i] = i - memberDelta;
2050 // modify just this child's view of the qualifier
2051 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2052 InheritQualifiers(memberQualifier, qualifier);
2053
2054 // manually inherit location; it's more complex
2055 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2056 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2057 if (qualifier.hasLocation())
2058 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2059
2060 // recurse
2061 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2062 }
2063 }
2064
2065 // Make the SPIR-V type
2066 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2067 if (! HasNonLayoutQualifiers(qualifier))
2068 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2069
2070 // Decorate it
2071 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2072
2073 return spvType;
2074}
2075
2076void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2077 const glslang::TTypeList* glslangMembers,
2078 glslang::TLayoutPacking explicitLayout,
2079 const glslang::TQualifier& qualifier,
2080 spv::Id spvType)
2081{
2082 // Name and decorate the non-hidden members
2083 int offset = -1;
2084 int locationOffset = 0; // for use within the members of this struct
2085 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2086 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2087 int member = i;
2088 if (type.getBasicType() == glslang::EbtBlock)
2089 member = memberRemapper[glslangMembers][i];
2090
2091 // modify just this child's view of the qualifier
2092 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2093 InheritQualifiers(memberQualifier, qualifier);
2094
2095 // using -1 above to indicate a hidden member
2096 if (member >= 0) {
2097 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2098 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2099 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2100 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2101 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2102 if (type.getBasicType() == glslang::EbtBlock) {
2103 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2104 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2105 }
2106 }
2107 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2108
2109 if (qualifier.storage == glslang::EvqBuffer) {
2110 std::vector<spv::Decoration> memory;
2111 TranslateMemoryDecoration(memberQualifier, memory);
2112 for (unsigned int i = 0; i < memory.size(); ++i)
2113 addMemberDecoration(spvType, member, memory[i]);
2114 }
2115
John Kessenich2f47bc92016-06-30 21:47:35 -06002116 // Compute location decoration; tricky based on whether inheritance is at play and
2117 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002118 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2119 // probably move to the linker stage of the front end proper, and just have the
2120 // answer sitting already distributed throughout the individual member locations.
2121 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002122 // Ignore member locations if the container is an array, as that's
2123 // ill-specified and decisions have been made to not allow this anyway.
2124 // The object itself must have a location, and that comes out from decorating the object,
2125 // not the type (this code decorates types).
2126 if (! type.isArray()) {
2127 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2128 // struct members should not have explicit locations
2129 assert(type.getBasicType() != glslang::EbtStruct);
2130 location = memberQualifier.layoutLocation;
2131 } else if (type.getBasicType() != glslang::EbtBlock) {
2132 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2133 // The members, and their nested types, must not themselves have Location decorations.
2134 } else if (qualifier.hasLocation()) // inheritance
2135 location = qualifier.layoutLocation + locationOffset;
2136 }
John Kessenich6090df02016-06-30 21:18:02 -06002137 if (location >= 0)
2138 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2139
John Kessenich2f47bc92016-06-30 21:47:35 -06002140 if (qualifier.hasLocation()) // track for upcoming inheritance
2141 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2142
John Kessenich6090df02016-06-30 21:18:02 -06002143 // component, XFB, others
2144 if (glslangMember.getQualifier().hasComponent())
2145 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2146 if (glslangMember.getQualifier().hasXfbOffset())
2147 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2148 else if (explicitLayout != glslang::ElpNone) {
2149 // figure out what to do with offset, which is accumulating
2150 int nextOffset;
2151 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2152 if (offset >= 0)
2153 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2154 offset = nextOffset;
2155 }
2156
2157 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2158 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2159
2160 // built-in variable decorations
2161 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002162 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002163 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2164 }
2165 }
2166
2167 // Decorate the structure
2168 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2169 addDecoration(spvType, TranslateBlockDecoration(type));
2170 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2171 builder.addCapability(spv::CapabilityGeometryStreams);
2172 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2173 }
2174 if (glslangIntermediate->getXfbMode()) {
2175 builder.addCapability(spv::CapabilityTransformFeedback);
2176 if (type.getQualifier().hasXfbStride())
2177 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2178 if (type.getQualifier().hasXfbBuffer())
2179 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2180 }
2181}
2182
John Kessenich6c292d32016-02-15 20:58:50 -07002183// Turn the expression forming the array size into an id.
2184// This is not quite trivial, because of specialization constants.
2185// Sometimes, a raw constant is turned into an Id, and sometimes
2186// a specialization constant expression is.
2187spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2188{
2189 // First, see if this is sized with a node, meaning a specialization constant:
2190 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2191 if (specNode != nullptr) {
2192 builder.clearAccessChain();
2193 specNode->traverse(this);
2194 return accessChainLoad(specNode->getAsTyped()->getType());
2195 }
qining25262b32016-05-06 17:25:16 -04002196
John Kessenich6c292d32016-02-15 20:58:50 -07002197 // Otherwise, need a compile-time (front end) size, get it:
2198 int size = arraySizes.getDimSize(dim);
2199 assert(size > 0);
2200 return builder.makeUintConstant(size);
2201}
2202
John Kessenich103bef92016-02-08 21:38:15 -07002203// Wrap the builder's accessChainLoad to:
2204// - localize handling of RelaxedPrecision
2205// - use the SPIR-V inferred type instead of another conversion of the glslang type
2206// (avoids unnecessary work and possible type punning for structures)
2207// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002208spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2209{
John Kessenich103bef92016-02-08 21:38:15 -07002210 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2211 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2212
2213 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002214 if (type.getBasicType() == glslang::EbtBool) {
2215 if (builder.isScalarType(nominalTypeId)) {
2216 // Conversion for bool
2217 spv::Id boolType = builder.makeBoolType();
2218 if (nominalTypeId != boolType)
2219 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2220 } else if (builder.isVectorType(nominalTypeId)) {
2221 // Conversion for bvec
2222 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2223 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2224 if (nominalTypeId != bvecType)
2225 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2226 }
2227 }
John Kessenich103bef92016-02-08 21:38:15 -07002228
2229 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002230}
2231
Rex Xu27253232016-02-23 17:51:09 +08002232// Wrap the builder's accessChainStore to:
2233// - do conversion of concrete to abstract type
2234void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2235{
2236 // Need to convert to abstract types when necessary
2237 if (type.getBasicType() == glslang::EbtBool) {
2238 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2239
2240 if (builder.isScalarType(nominalTypeId)) {
2241 // Conversion for bool
2242 spv::Id boolType = builder.makeBoolType();
2243 if (nominalTypeId != boolType) {
2244 spv::Id zero = builder.makeUintConstant(0);
2245 spv::Id one = builder.makeUintConstant(1);
2246 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2247 }
2248 } else if (builder.isVectorType(nominalTypeId)) {
2249 // Conversion for bvec
2250 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2251 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2252 if (nominalTypeId != bvecType) {
2253 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2254 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2255 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2256 }
2257 }
2258 }
2259
2260 builder.accessChainStore(rvalue);
2261}
2262
John Kessenichf85e8062015-12-19 13:57:10 -07002263// Decide whether or not this type should be
2264// decorated with offsets and strides, and if so
2265// whether std140 or std430 rules should be applied.
2266glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002267{
John Kessenichf85e8062015-12-19 13:57:10 -07002268 // has to be a block
2269 if (type.getBasicType() != glslang::EbtBlock)
2270 return glslang::ElpNone;
2271
2272 // has to be a uniform or buffer block
2273 if (type.getQualifier().storage != glslang::EvqUniform &&
2274 type.getQualifier().storage != glslang::EvqBuffer)
2275 return glslang::ElpNone;
2276
2277 // return the layout to use
2278 switch (type.getQualifier().layoutPacking) {
2279 case glslang::ElpStd140:
2280 case glslang::ElpStd430:
2281 return type.getQualifier().layoutPacking;
2282 default:
2283 return glslang::ElpNone;
2284 }
John Kessenich31ed4832015-09-09 17:51:38 -06002285}
2286
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002287// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002288int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002289{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002290 int size;
John Kessenich49987892015-12-29 17:11:44 -07002291 int stride;
2292 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002293
2294 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002295}
2296
John Kessenich49987892015-12-29 17:11:44 -07002297// 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 -07002298// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002299int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002300{
John Kessenich49987892015-12-29 17:11:44 -07002301 glslang::TType elementType;
2302 elementType.shallowCopy(matrixType);
2303 elementType.clearArraySizes();
2304
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002305 int size;
John Kessenich49987892015-12-29 17:11:44 -07002306 int stride;
2307 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2308
2309 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002310}
2311
John Kessenich5e4b1242015-08-06 22:53:06 -06002312// Given a member type of a struct, realign the current offset for it, and compute
2313// the next (not yet aligned) offset for the next member, which will get aligned
2314// on the next call.
2315// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2316// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2317// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002318void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002319 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002320{
2321 // this will get a positive value when deemed necessary
2322 nextOffset = -1;
2323
John Kessenich5e4b1242015-08-06 22:53:06 -06002324 // override anything in currentOffset with user-set offset
2325 if (memberType.getQualifier().hasOffset())
2326 currentOffset = memberType.getQualifier().layoutOffset;
2327
2328 // It could be that current linker usage in glslang updated all the layoutOffset,
2329 // in which case the following code does not matter. But, that's not quite right
2330 // once cross-compilation unit GLSL validation is done, as the original user
2331 // settings are needed in layoutOffset, and then the following will come into play.
2332
John Kessenichf85e8062015-12-19 13:57:10 -07002333 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002334 if (! memberType.getQualifier().hasOffset())
2335 currentOffset = -1;
2336
2337 return;
2338 }
2339
John Kessenichf85e8062015-12-19 13:57:10 -07002340 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002341 if (currentOffset < 0)
2342 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002343
John Kessenich5e4b1242015-08-06 22:53:06 -06002344 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2345 // but possibly not yet correctly aligned.
2346
2347 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002348 int dummyStride;
2349 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002350 glslang::RoundToPow2(currentOffset, memberAlignment);
2351 nextOffset = currentOffset + memberSize;
2352}
2353
David Netoa901ffe2016-06-08 14:11:40 +01002354void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002355{
David Netoa901ffe2016-06-08 14:11:40 +01002356 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2357 switch (glslangBuiltIn)
2358 {
2359 case glslang::EbvClipDistance:
2360 case glslang::EbvCullDistance:
2361 case glslang::EbvPointSize:
2362 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2363 // Alternately, we could just call this for any glslang built-in, since the
2364 // capability already guards against duplicates.
2365 TranslateBuiltInDecoration(glslangBuiltIn, false);
2366 break;
2367 default:
2368 // Capabilities were already generated when the struct was declared.
2369 break;
2370 }
John Kessenichebb50532016-05-16 19:22:05 -06002371}
2372
John Kessenich140f3df2015-06-26 16:58:36 -06002373bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2374{
John Kessenich4d65ee32016-03-12 18:17:47 -07002375 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002376 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002377 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002378}
2379
2380// Make all the functions, skeletally, without actually visiting their bodies.
2381void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2382{
2383 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2384 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2385 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2386 continue;
2387
2388 // We're on a user function. Set up the basic interface for the function now,
2389 // so that it's available to call.
2390 // Translating the body will happen later.
2391 //
qining25262b32016-05-06 17:25:16 -04002392 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002393 // function. What it is an address of varies:
2394 //
2395 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2396 // so that write needs to be to a copy, hence the address of a copy works.
2397 //
2398 // - "const in" parameters can just be the r-value, as no writes need occur.
2399 //
2400 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2401 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2402
2403 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002404 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002405 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2406
2407 for (int p = 0; p < (int)parameters.size(); ++p) {
2408 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2409 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002410 if (paramType.isOpaque())
2411 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2412 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002413 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2414 else
2415 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002416 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002417 paramTypes.push_back(typeId);
2418 }
2419
2420 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002421 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2422 convertGlslangToSpvType(glslFunction->getType()),
2423 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002424
2425 // Track function to emit/call later
2426 functionMap[glslFunction->getName().c_str()] = function;
2427
2428 // Set the parameter id's
2429 for (int p = 0; p < (int)parameters.size(); ++p) {
2430 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2431 // give a name too
2432 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2433 }
2434 }
2435}
2436
2437// Process all the initializers, while skipping the functions and link objects
2438void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2439{
2440 builder.setBuildPoint(shaderEntry->getLastBlock());
2441 for (int i = 0; i < (int)initializers.size(); ++i) {
2442 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2443 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2444
2445 // We're on a top-level node that's not a function. Treat as an initializer, whose
2446 // code goes into the beginning of main.
2447 initializer->traverse(this);
2448 }
2449 }
2450}
2451
2452// Process all the functions, while skipping initializers.
2453void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2454{
2455 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2456 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2457 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2458 node->traverse(this);
2459 }
2460}
2461
2462void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2463{
qining25262b32016-05-06 17:25:16 -04002464 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002465 // that called makeFunctions().
2466 spv::Function* function = functionMap[node->getName().c_str()];
2467 spv::Block* functionBlock = function->getEntryBlock();
2468 builder.setBuildPoint(functionBlock);
2469}
2470
Rex Xu04db3f52015-09-16 11:44:02 +08002471void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002472{
Rex Xufc618912015-09-09 16:42:49 +08002473 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002474
2475 glslang::TSampler sampler = {};
2476 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002477 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002478 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2479 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2480 }
2481
John Kessenich140f3df2015-06-26 16:58:36 -06002482 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2483 builder.clearAccessChain();
2484 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002485
2486 // Special case l-value operands
2487 bool lvalue = false;
2488 switch (node.getOp()) {
2489 case glslang::EOpImageAtomicAdd:
2490 case glslang::EOpImageAtomicMin:
2491 case glslang::EOpImageAtomicMax:
2492 case glslang::EOpImageAtomicAnd:
2493 case glslang::EOpImageAtomicOr:
2494 case glslang::EOpImageAtomicXor:
2495 case glslang::EOpImageAtomicExchange:
2496 case glslang::EOpImageAtomicCompSwap:
2497 if (i == 0)
2498 lvalue = true;
2499 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002500 case glslang::EOpSparseImageLoad:
2501 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2502 lvalue = true;
2503 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002504 case glslang::EOpSparseTexture:
2505 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2506 lvalue = true;
2507 break;
2508 case glslang::EOpSparseTextureClamp:
2509 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2510 lvalue = true;
2511 break;
2512 case glslang::EOpSparseTextureLod:
2513 case glslang::EOpSparseTextureOffset:
2514 if (i == 3)
2515 lvalue = true;
2516 break;
2517 case glslang::EOpSparseTextureFetch:
2518 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2519 lvalue = true;
2520 break;
2521 case glslang::EOpSparseTextureFetchOffset:
2522 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2523 lvalue = true;
2524 break;
2525 case glslang::EOpSparseTextureLodOffset:
2526 case glslang::EOpSparseTextureGrad:
2527 case glslang::EOpSparseTextureOffsetClamp:
2528 if (i == 4)
2529 lvalue = true;
2530 break;
2531 case glslang::EOpSparseTextureGradOffset:
2532 case glslang::EOpSparseTextureGradClamp:
2533 if (i == 5)
2534 lvalue = true;
2535 break;
2536 case glslang::EOpSparseTextureGradOffsetClamp:
2537 if (i == 6)
2538 lvalue = true;
2539 break;
2540 case glslang::EOpSparseTextureGather:
2541 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2542 lvalue = true;
2543 break;
2544 case glslang::EOpSparseTextureGatherOffset:
2545 case glslang::EOpSparseTextureGatherOffsets:
2546 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2547 lvalue = true;
2548 break;
Rex Xufc618912015-09-09 16:42:49 +08002549 default:
2550 break;
2551 }
2552
Rex Xu6b86d492015-09-16 17:48:22 +08002553 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002554 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002555 else
John Kessenich32cfd492016-02-02 12:37:46 -07002556 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002557 }
2558}
2559
John Kessenichfc51d282015-08-19 13:34:18 -06002560void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002561{
John Kessenichfc51d282015-08-19 13:34:18 -06002562 builder.clearAccessChain();
2563 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002564 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002565}
John Kessenich140f3df2015-06-26 16:58:36 -06002566
John Kessenichfc51d282015-08-19 13:34:18 -06002567spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2568{
Rex Xufc618912015-09-09 16:42:49 +08002569 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002570 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002571 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002572 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002573
John Kessenichfc51d282015-08-19 13:34:18 -06002574 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002575 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2576 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2577 std::vector<spv::Id> arguments;
2578 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002579 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002580 else
2581 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002582 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002583
2584 spv::Builder::TextureParameters params = { };
2585 params.sampler = arguments[0];
2586
Rex Xu04db3f52015-09-16 11:44:02 +08002587 glslang::TCrackedTextureOp cracked;
2588 node->crackTexture(sampler, cracked);
2589
John Kessenichfc51d282015-08-19 13:34:18 -06002590 // Check for queries
2591 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002592 // a sampled image needs to have the image extracted first
2593 if (builder.isSampledImage(params.sampler))
2594 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002595 switch (node->getOp()) {
2596 case glslang::EOpImageQuerySize:
2597 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002598 if (arguments.size() > 1) {
2599 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002600 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002601 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002602 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002603 case glslang::EOpImageQuerySamples:
2604 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002605 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002606 case glslang::EOpTextureQueryLod:
2607 params.coords = arguments[1];
2608 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2609 case glslang::EOpTextureQueryLevels:
2610 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002611 case glslang::EOpSparseTexelsResident:
2612 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002613 default:
2614 assert(0);
2615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002616 }
John Kessenich140f3df2015-06-26 16:58:36 -06002617 }
2618
Rex Xufc618912015-09-09 16:42:49 +08002619 // Check for image functions other than queries
2620 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002621 std::vector<spv::Id> operands;
2622 auto opIt = arguments.begin();
2623 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002624
2625 // Handle subpass operations
2626 // TODO: GLSL should change to have the "MS" only on the type rather than the
2627 // built-in function.
2628 if (cracked.subpass) {
2629 // add on the (0,0) coordinate
2630 spv::Id zero = builder.makeIntConstant(0);
2631 std::vector<spv::Id> comps;
2632 comps.push_back(zero);
2633 comps.push_back(zero);
2634 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2635 if (sampler.ms) {
2636 operands.push_back(spv::ImageOperandsSampleMask);
2637 operands.push_back(*(opIt++));
2638 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002639 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002640 }
2641
John Kessenich56bab042015-09-16 10:54:31 -06002642 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002643 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002644 if (sampler.ms) {
2645 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002646 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002647 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002648 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2649 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002650 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002651 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002652 if (sampler.ms) {
2653 operands.push_back(*(opIt + 1));
2654 operands.push_back(spv::ImageOperandsSampleMask);
2655 operands.push_back(*opIt);
2656 } else
2657 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002658 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002659 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2660 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002661 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002662 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2663 builder.addCapability(spv::CapabilitySparseResidency);
2664 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2665 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2666
2667 if (sampler.ms) {
2668 operands.push_back(spv::ImageOperandsSampleMask);
2669 operands.push_back(*opIt++);
2670 }
2671
2672 // Create the return type that was a special structure
2673 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002674 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002675 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2676 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2677
2678 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2679
2680 // Decode the return type
2681 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2682 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002683 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002684 // Process image atomic operations
2685
2686 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2687 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002688 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002689
John Kessenich8c8505c2016-07-26 12:50:38 -06002690 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002691 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002692
2693 std::vector<spv::Id> operands;
2694 operands.push_back(pointer);
2695 for (; opIt != arguments.end(); ++opIt)
2696 operands.push_back(*opIt);
2697
John Kessenich8c8505c2016-07-26 12:50:38 -06002698 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002699 }
2700 }
2701
2702 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002703 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002704 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2705
John Kessenichfc51d282015-08-19 13:34:18 -06002706 // check for bias argument
2707 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002708 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002709 int nonBiasArgCount = 2;
2710 if (cracked.offset)
2711 ++nonBiasArgCount;
2712 if (cracked.grad)
2713 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002714 if (cracked.lodClamp)
2715 ++nonBiasArgCount;
2716 if (sparse)
2717 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002718
2719 if ((int)arguments.size() > nonBiasArgCount)
2720 bias = true;
2721 }
2722
John Kessenicha5c33d62016-06-02 23:45:21 -06002723 // See if the sampler param should really be just the SPV image part
2724 if (cracked.fetch) {
2725 // a fetch needs to have the image extracted first
2726 if (builder.isSampledImage(params.sampler))
2727 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2728 }
2729
John Kessenichfc51d282015-08-19 13:34:18 -06002730 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002731
John Kessenichfc51d282015-08-19 13:34:18 -06002732 params.coords = arguments[1];
2733 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002734 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002735
2736 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002737 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002738 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002739 ++extraArgs;
2740 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002741 params.Dref = arguments[2];
2742 ++extraArgs;
2743 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002744 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002745 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002746 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002747 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002748 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002749 dRefComp = builder.getNumComponents(params.coords) - 1;
2750 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002751 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2752 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002753
2754 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002755 if (cracked.lod) {
2756 params.lod = arguments[2];
2757 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002758 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2759 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2760 noImplicitLod = true;
2761 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002762
2763 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002764 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002765 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002766 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002767 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002768
2769 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002770 if (cracked.grad) {
2771 params.gradX = arguments[2 + extraArgs];
2772 params.gradY = arguments[3 + extraArgs];
2773 extraArgs += 2;
2774 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002775
2776 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002777 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002778 params.offset = arguments[2 + extraArgs];
2779 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002780 } else if (cracked.offsets) {
2781 params.offsets = arguments[2 + extraArgs];
2782 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002783 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002784
2785 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002786 if (cracked.lodClamp) {
2787 params.lodClamp = arguments[2 + extraArgs];
2788 ++extraArgs;
2789 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002790
2791 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002792 if (sparse) {
2793 params.texelOut = arguments[2 + extraArgs];
2794 ++extraArgs;
2795 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002796
2797 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002798 if (bias) {
2799 params.bias = arguments[2 + extraArgs];
2800 ++extraArgs;
2801 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002802
2803 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002804 if (cracked.gather && ! sampler.shadow) {
2805 // default component is 0, if missing, otherwise an argument
2806 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002807 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002808 ++extraArgs;
2809 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002810 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002811 }
2812 }
John Kessenichfc51d282015-08-19 13:34:18 -06002813
John Kessenich65336482016-06-16 14:06:26 -06002814 // projective component (might not to move)
2815 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2816 // are divided by the last component of P."
2817 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2818 // unused components will appear after all used components."
2819 if (cracked.proj) {
2820 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2821 int projTargetComp;
2822 switch (sampler.dim) {
2823 case glslang::Esd1D: projTargetComp = 1; break;
2824 case glslang::Esd2D: projTargetComp = 2; break;
2825 case glslang::EsdRect: projTargetComp = 2; break;
2826 default: projTargetComp = projSourceComp; break;
2827 }
2828 // copy the projective coordinate if we have to
2829 if (projTargetComp != projSourceComp) {
2830 spv::Id projComp = builder.createCompositeExtract(params.coords,
2831 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2832 projSourceComp);
2833 params.coords = builder.createCompositeInsert(projComp, params.coords,
2834 builder.getTypeId(params.coords), projTargetComp);
2835 }
2836 }
2837
John Kessenich8c8505c2016-07-26 12:50:38 -06002838 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002839}
2840
2841spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2842{
2843 // Grab the function's pointer from the previously created function
2844 spv::Function* function = functionMap[node->getName().c_str()];
2845 if (! function)
2846 return 0;
2847
2848 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2849 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2850
2851 // See comments in makeFunctions() for details about the semantics for parameter passing.
2852 //
2853 // These imply we need a four step process:
2854 // 1. Evaluate the arguments
2855 // 2. Allocate and make copies of in, out, and inout arguments
2856 // 3. Make the call
2857 // 4. Copy back the results
2858
2859 // 1. Evaluate the arguments
2860 std::vector<spv::Builder::AccessChain> lValues;
2861 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002862 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002863 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002864 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002865 // build l-value
2866 builder.clearAccessChain();
2867 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002868 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002869 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002870 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002871 // save l-value
2872 lValues.push_back(builder.getAccessChain());
2873 } else {
2874 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002875 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002876 }
2877 }
2878
2879 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2880 // copy the original into that space.
2881 //
2882 // Also, build up the list of actual arguments to pass in for the call
2883 int lValueCount = 0;
2884 int rValueCount = 0;
2885 std::vector<spv::Id> spvArgs;
2886 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002887 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002888 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002889 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002890 builder.setAccessChain(lValues[lValueCount]);
2891 arg = builder.accessChainGetLValue();
2892 ++lValueCount;
2893 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002894 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002895 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2896 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2897 // need to copy the input into output space
2898 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002899 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002900 builder.createStore(copy, arg);
2901 }
2902 ++lValueCount;
2903 } else {
2904 arg = rValues[rValueCount];
2905 ++rValueCount;
2906 }
2907 spvArgs.push_back(arg);
2908 }
2909
2910 // 3. Make the call.
2911 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002912 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002913
2914 // 4. Copy back out an "out" arguments.
2915 lValueCount = 0;
2916 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2917 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2918 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2919 spv::Id copy = builder.createLoad(spvArgs[a]);
2920 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002921 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002922 }
2923 ++lValueCount;
2924 }
2925 }
2926
2927 return result;
2928}
2929
2930// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002931spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2932 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002933 spv::Id typeId, spv::Id left, spv::Id right,
2934 glslang::TBasicType typeProxy, bool reduceComparison)
2935{
Rex Xu8ff43de2016-04-22 16:51:45 +08002936 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002938 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002939
2940 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002941 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002942 bool comparison = false;
2943
2944 switch (op) {
2945 case glslang::EOpAdd:
2946 case glslang::EOpAddAssign:
2947 if (isFloat)
2948 binOp = spv::OpFAdd;
2949 else
2950 binOp = spv::OpIAdd;
2951 break;
2952 case glslang::EOpSub:
2953 case glslang::EOpSubAssign:
2954 if (isFloat)
2955 binOp = spv::OpFSub;
2956 else
2957 binOp = spv::OpISub;
2958 break;
2959 case glslang::EOpMul:
2960 case glslang::EOpMulAssign:
2961 if (isFloat)
2962 binOp = spv::OpFMul;
2963 else
2964 binOp = spv::OpIMul;
2965 break;
2966 case glslang::EOpVectorTimesScalar:
2967 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002968 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002969 if (builder.isVector(right))
2970 std::swap(left, right);
2971 assert(builder.isScalar(right));
2972 needMatchingVectors = false;
2973 binOp = spv::OpVectorTimesScalar;
2974 } else
2975 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpVectorTimesMatrix:
2978 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002979 binOp = spv::OpVectorTimesMatrix;
2980 break;
2981 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002982 binOp = spv::OpMatrixTimesVector;
2983 break;
2984 case glslang::EOpMatrixTimesScalar:
2985 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002986 binOp = spv::OpMatrixTimesScalar;
2987 break;
2988 case glslang::EOpMatrixTimesMatrix:
2989 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002990 binOp = spv::OpMatrixTimesMatrix;
2991 break;
2992 case glslang::EOpOuterProduct:
2993 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002994 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002995 break;
2996
2997 case glslang::EOpDiv:
2998 case glslang::EOpDivAssign:
2999 if (isFloat)
3000 binOp = spv::OpFDiv;
3001 else if (isUnsigned)
3002 binOp = spv::OpUDiv;
3003 else
3004 binOp = spv::OpSDiv;
3005 break;
3006 case glslang::EOpMod:
3007 case glslang::EOpModAssign:
3008 if (isFloat)
3009 binOp = spv::OpFMod;
3010 else if (isUnsigned)
3011 binOp = spv::OpUMod;
3012 else
3013 binOp = spv::OpSMod;
3014 break;
3015 case glslang::EOpRightShift:
3016 case glslang::EOpRightShiftAssign:
3017 if (isUnsigned)
3018 binOp = spv::OpShiftRightLogical;
3019 else
3020 binOp = spv::OpShiftRightArithmetic;
3021 break;
3022 case glslang::EOpLeftShift:
3023 case glslang::EOpLeftShiftAssign:
3024 binOp = spv::OpShiftLeftLogical;
3025 break;
3026 case glslang::EOpAnd:
3027 case glslang::EOpAndAssign:
3028 binOp = spv::OpBitwiseAnd;
3029 break;
3030 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003031 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 binOp = spv::OpLogicalAnd;
3033 break;
3034 case glslang::EOpInclusiveOr:
3035 case glslang::EOpInclusiveOrAssign:
3036 binOp = spv::OpBitwiseOr;
3037 break;
3038 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003039 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003040 binOp = spv::OpLogicalOr;
3041 break;
3042 case glslang::EOpExclusiveOr:
3043 case glslang::EOpExclusiveOrAssign:
3044 binOp = spv::OpBitwiseXor;
3045 break;
3046 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003047 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003048 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 break;
3050
3051 case glslang::EOpLessThan:
3052 case glslang::EOpGreaterThan:
3053 case glslang::EOpLessThanEqual:
3054 case glslang::EOpGreaterThanEqual:
3055 case glslang::EOpEqual:
3056 case glslang::EOpNotEqual:
3057 case glslang::EOpVectorEqual:
3058 case glslang::EOpVectorNotEqual:
3059 comparison = true;
3060 break;
3061 default:
3062 break;
3063 }
3064
John Kessenich7c1aa102015-10-15 13:29:11 -06003065 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003066 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003067 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003068 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003069 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003070
3071 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003072 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003073 builder.promoteScalar(precision, left, right);
3074
qining25262b32016-05-06 17:25:16 -04003075 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3076 addDecoration(result, noContraction);
3077 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003078 }
3079
3080 if (! comparison)
3081 return 0;
3082
John Kessenich7c1aa102015-10-15 13:29:11 -06003083 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003084
3085 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
3086 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
3087
John Kessenich22118352015-12-21 20:54:09 -07003088 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003089 }
3090
3091 switch (op) {
3092 case glslang::EOpLessThan:
3093 if (isFloat)
3094 binOp = spv::OpFOrdLessThan;
3095 else if (isUnsigned)
3096 binOp = spv::OpULessThan;
3097 else
3098 binOp = spv::OpSLessThan;
3099 break;
3100 case glslang::EOpGreaterThan:
3101 if (isFloat)
3102 binOp = spv::OpFOrdGreaterThan;
3103 else if (isUnsigned)
3104 binOp = spv::OpUGreaterThan;
3105 else
3106 binOp = spv::OpSGreaterThan;
3107 break;
3108 case glslang::EOpLessThanEqual:
3109 if (isFloat)
3110 binOp = spv::OpFOrdLessThanEqual;
3111 else if (isUnsigned)
3112 binOp = spv::OpULessThanEqual;
3113 else
3114 binOp = spv::OpSLessThanEqual;
3115 break;
3116 case glslang::EOpGreaterThanEqual:
3117 if (isFloat)
3118 binOp = spv::OpFOrdGreaterThanEqual;
3119 else if (isUnsigned)
3120 binOp = spv::OpUGreaterThanEqual;
3121 else
3122 binOp = spv::OpSGreaterThanEqual;
3123 break;
3124 case glslang::EOpEqual:
3125 case glslang::EOpVectorEqual:
3126 if (isFloat)
3127 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003128 else if (isBool)
3129 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 else
3131 binOp = spv::OpIEqual;
3132 break;
3133 case glslang::EOpNotEqual:
3134 case glslang::EOpVectorNotEqual:
3135 if (isFloat)
3136 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003137 else if (isBool)
3138 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003139 else
3140 binOp = spv::OpINotEqual;
3141 break;
3142 default:
3143 break;
3144 }
3145
qining25262b32016-05-06 17:25:16 -04003146 if (binOp != spv::OpNop) {
3147 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3148 addDecoration(result, noContraction);
3149 return builder.setPrecision(result, precision);
3150 }
John Kessenich140f3df2015-06-26 16:58:36 -06003151
3152 return 0;
3153}
3154
John Kessenich04bb8a02015-12-12 12:28:14 -07003155//
3156// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3157// These can be any of:
3158//
3159// matrix * scalar
3160// scalar * matrix
3161// matrix * matrix linear algebraic
3162// matrix * vector
3163// vector * matrix
3164// matrix * matrix componentwise
3165// matrix op matrix op in {+, -, /}
3166// matrix op scalar op in {+, -, /}
3167// scalar op matrix op in {+, -, /}
3168//
qining25262b32016-05-06 17:25:16 -04003169spv::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 -07003170{
3171 bool firstClass = true;
3172
3173 // First, handle first-class matrix operations (* and matrix/scalar)
3174 switch (op) {
3175 case spv::OpFDiv:
3176 if (builder.isMatrix(left) && builder.isScalar(right)) {
3177 // turn matrix / scalar into a multiply...
3178 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3179 op = spv::OpMatrixTimesScalar;
3180 } else
3181 firstClass = false;
3182 break;
3183 case spv::OpMatrixTimesScalar:
3184 if (builder.isMatrix(right))
3185 std::swap(left, right);
3186 assert(builder.isScalar(right));
3187 break;
3188 case spv::OpVectorTimesMatrix:
3189 assert(builder.isVector(left));
3190 assert(builder.isMatrix(right));
3191 break;
3192 case spv::OpMatrixTimesVector:
3193 assert(builder.isMatrix(left));
3194 assert(builder.isVector(right));
3195 break;
3196 case spv::OpMatrixTimesMatrix:
3197 assert(builder.isMatrix(left));
3198 assert(builder.isMatrix(right));
3199 break;
3200 default:
3201 firstClass = false;
3202 break;
3203 }
3204
qining25262b32016-05-06 17:25:16 -04003205 if (firstClass) {
3206 spv::Id result = builder.createBinOp(op, typeId, left, right);
3207 addDecoration(result, noContraction);
3208 return builder.setPrecision(result, precision);
3209 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003210
LoopDawg592860c2016-06-09 08:57:35 -06003211 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003212 // The result type of all of them is the same type as the (a) matrix operand.
3213 // The algorithm is to:
3214 // - break the matrix(es) into vectors
3215 // - smear any scalar to a vector
3216 // - do vector operations
3217 // - make a matrix out the vector results
3218 switch (op) {
3219 case spv::OpFAdd:
3220 case spv::OpFSub:
3221 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003222 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003223 case spv::OpFMul:
3224 {
3225 // one time set up...
3226 bool leftMat = builder.isMatrix(left);
3227 bool rightMat = builder.isMatrix(right);
3228 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3229 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3230 spv::Id scalarType = builder.getScalarTypeId(typeId);
3231 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3232 std::vector<spv::Id> results;
3233 spv::Id smearVec = spv::NoResult;
3234 if (builder.isScalar(left))
3235 smearVec = builder.smearScalar(precision, left, vecType);
3236 else if (builder.isScalar(right))
3237 smearVec = builder.smearScalar(precision, right, vecType);
3238
3239 // do each vector op
3240 for (unsigned int c = 0; c < numCols; ++c) {
3241 std::vector<unsigned int> indexes;
3242 indexes.push_back(c);
3243 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3244 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003245 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3246 addDecoration(result, noContraction);
3247 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003248 }
3249
3250 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003251 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003252 }
3253 default:
3254 assert(0);
3255 return spv::NoResult;
3256 }
3257}
3258
qining25262b32016-05-06 17:25:16 -04003259spv::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 -06003260{
3261 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003262 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003264 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003265 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003266
3267 switch (op) {
3268 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003269 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003270 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003271 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003272 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003273 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003274 unaryOp = spv::OpSNegate;
3275 break;
3276
3277 case glslang::EOpLogicalNot:
3278 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003279 unaryOp = spv::OpLogicalNot;
3280 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003281 case glslang::EOpBitwiseNot:
3282 unaryOp = spv::OpNot;
3283 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003284
John Kessenich140f3df2015-06-26 16:58:36 -06003285 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003286 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003287 break;
3288 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003289 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003290 break;
3291 case glslang::EOpTranspose:
3292 unaryOp = spv::OpTranspose;
3293 break;
3294
3295 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003296 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003297 break;
3298 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003299 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003300 break;
3301 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003302 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003303 break;
3304 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003305 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003306 break;
3307 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003308 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003309 break;
3310 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003311 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003312 break;
3313 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003314 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003315 break;
3316 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003317 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 break;
3319
3320 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003321 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003322 break;
3323 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003324 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003325 break;
3326 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003328 break;
3329 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003330 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003331 break;
3332 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003333 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003334 break;
3335 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003336 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003337 break;
3338
3339 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003340 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003341 break;
3342 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003343 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003344 break;
3345
3346 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003350 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003351 break;
3352 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003353 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003354 break;
3355 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003356 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003357 break;
3358 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003359 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003360 break;
3361 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003362 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003363 break;
3364
3365 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003366 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003367 break;
3368 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003369 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003370 break;
3371 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003372 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 break;
3374 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003375 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003376 break;
3377 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003378 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003381 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003382 break;
3383
3384 case glslang::EOpIsNan:
3385 unaryOp = spv::OpIsNan;
3386 break;
3387 case glslang::EOpIsInf:
3388 unaryOp = spv::OpIsInf;
3389 break;
LoopDawg592860c2016-06-09 08:57:35 -06003390 case glslang::EOpIsFinite:
3391 unaryOp = spv::OpIsFinite;
3392 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003393
Rex Xucbc426e2015-12-15 16:03:10 +08003394 case glslang::EOpFloatBitsToInt:
3395 case glslang::EOpFloatBitsToUint:
3396 case glslang::EOpIntBitsToFloat:
3397 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003398 case glslang::EOpDoubleBitsToInt64:
3399 case glslang::EOpDoubleBitsToUint64:
3400 case glslang::EOpInt64BitsToDouble:
3401 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003402 unaryOp = spv::OpBitcast;
3403 break;
3404
John Kessenich140f3df2015-06-26 16:58:36 -06003405 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003410 break;
3411 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003415 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
3417 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003418 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003419 break;
3420 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003421 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003422 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003423 case glslang::EOpPackSnorm4x8:
3424 libCall = spv::GLSLstd450PackSnorm4x8;
3425 break;
3426 case glslang::EOpUnpackSnorm4x8:
3427 libCall = spv::GLSLstd450UnpackSnorm4x8;
3428 break;
3429 case glslang::EOpPackUnorm4x8:
3430 libCall = spv::GLSLstd450PackUnorm4x8;
3431 break;
3432 case glslang::EOpUnpackUnorm4x8:
3433 libCall = spv::GLSLstd450UnpackUnorm4x8;
3434 break;
3435 case glslang::EOpPackDouble2x32:
3436 libCall = spv::GLSLstd450PackDouble2x32;
3437 break;
3438 case glslang::EOpUnpackDouble2x32:
3439 libCall = spv::GLSLstd450UnpackDouble2x32;
3440 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003441
Rex Xu8ff43de2016-04-22 16:51:45 +08003442 case glslang::EOpPackInt2x32:
3443 case glslang::EOpUnpackInt2x32:
3444 case glslang::EOpPackUint2x32:
3445 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003446 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003447 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3448 break;
3449
John Kessenich140f3df2015-06-26 16:58:36 -06003450 case glslang::EOpDPdx:
3451 unaryOp = spv::OpDPdx;
3452 break;
3453 case glslang::EOpDPdy:
3454 unaryOp = spv::OpDPdy;
3455 break;
3456 case glslang::EOpFwidth:
3457 unaryOp = spv::OpFwidth;
3458 break;
3459 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003460 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003461 unaryOp = spv::OpDPdxFine;
3462 break;
3463 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003464 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003465 unaryOp = spv::OpDPdyFine;
3466 break;
3467 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003468 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003469 unaryOp = spv::OpFwidthFine;
3470 break;
3471 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003472 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003473 unaryOp = spv::OpDPdxCoarse;
3474 break;
3475 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003476 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003477 unaryOp = spv::OpDPdyCoarse;
3478 break;
3479 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003480 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003481 unaryOp = spv::OpFwidthCoarse;
3482 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003483 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003484 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003485 libCall = spv::GLSLstd450InterpolateAtCentroid;
3486 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003487 case glslang::EOpAny:
3488 unaryOp = spv::OpAny;
3489 break;
3490 case glslang::EOpAll:
3491 unaryOp = spv::OpAll;
3492 break;
3493
3494 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 if (isFloat)
3496 libCall = spv::GLSLstd450FAbs;
3497 else
3498 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 if (isFloat)
3502 libCall = spv::GLSLstd450FSign;
3503 else
3504 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003505 break;
3506
John Kessenichfc51d282015-08-19 13:34:18 -06003507 case glslang::EOpAtomicCounterIncrement:
3508 case glslang::EOpAtomicCounterDecrement:
3509 case glslang::EOpAtomicCounter:
3510 {
3511 // Handle all of the atomics in one place, in createAtomicOperation()
3512 std::vector<spv::Id> operands;
3513 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003514 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003515 }
3516
John Kessenichfc51d282015-08-19 13:34:18 -06003517 case glslang::EOpBitFieldReverse:
3518 unaryOp = spv::OpBitReverse;
3519 break;
3520 case glslang::EOpBitCount:
3521 unaryOp = spv::OpBitCount;
3522 break;
3523 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003524 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003525 break;
3526 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003527 if (isUnsigned)
3528 libCall = spv::GLSLstd450FindUMsb;
3529 else
3530 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003531 break;
3532
Rex Xu574ab042016-04-14 16:53:07 +08003533 case glslang::EOpBallot:
3534 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003535 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003536 libCall = spv::GLSLstd450Bad;
3537 break;
3538
Rex Xu338b1852016-05-05 20:38:33 +08003539 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003540 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003541 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003542#ifdef AMD_EXTENSIONS
3543 case glslang::EOpMinInvocations:
3544 case glslang::EOpMaxInvocations:
3545 case glslang::EOpAddInvocations:
3546 case glslang::EOpMinInvocationsNonUniform:
3547 case glslang::EOpMaxInvocationsNonUniform:
3548 case glslang::EOpAddInvocationsNonUniform:
3549#endif
3550 return createInvocationsOperation(op, typeId, operand, typeProxy);
3551
3552#ifdef AMD_EXTENSIONS
3553 case glslang::EOpMbcnt:
3554 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3555 libCall = spv::MbcntAMD;
3556 break;
3557
3558 case glslang::EOpCubeFaceIndex:
3559 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3560 libCall = spv::CubeFaceIndexAMD;
3561 break;
3562
3563 case glslang::EOpCubeFaceCoord:
3564 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3565 libCall = spv::CubeFaceCoordAMD;
3566 break;
3567#endif
Rex Xu338b1852016-05-05 20:38:33 +08003568
John Kessenich140f3df2015-06-26 16:58:36 -06003569 default:
3570 return 0;
3571 }
3572
3573 spv::Id id;
3574 if (libCall >= 0) {
3575 std::vector<spv::Id> args;
3576 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003577 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003578 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003579 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003580 }
John Kessenich140f3df2015-06-26 16:58:36 -06003581
qining25262b32016-05-06 17:25:16 -04003582 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003583 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003584}
3585
John Kessenich7a53f762016-01-20 11:19:27 -07003586// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003587spv::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 -07003588{
3589 // Handle unary operations vector by vector.
3590 // The result type is the same type as the original type.
3591 // The algorithm is to:
3592 // - break the matrix into vectors
3593 // - apply the operation to each vector
3594 // - make a matrix out the vector results
3595
3596 // get the types sorted out
3597 int numCols = builder.getNumColumns(operand);
3598 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003599 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3600 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003601 std::vector<spv::Id> results;
3602
3603 // do each vector op
3604 for (int c = 0; c < numCols; ++c) {
3605 std::vector<unsigned int> indexes;
3606 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003607 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3608 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3609 addDecoration(destVec, noContraction);
3610 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003611 }
3612
3613 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003614 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003615}
3616
Rex Xu73e3ce72016-04-27 18:48:17 +08003617spv::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 -06003618{
3619 spv::Op convOp = spv::OpNop;
3620 spv::Id zero = 0;
3621 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003622 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003623
3624 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3625
3626 switch (op) {
3627 case glslang::EOpConvIntToBool:
3628 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003629 case glslang::EOpConvInt64ToBool:
3630 case glslang::EOpConvUint64ToBool:
3631 zero = (op == glslang::EOpConvInt64ToBool ||
3632 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003633 zero = makeSmearedConstant(zero, vectorSize);
3634 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3635
3636 case glslang::EOpConvFloatToBool:
3637 zero = builder.makeFloatConstant(0.0F);
3638 zero = makeSmearedConstant(zero, vectorSize);
3639 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3640
3641 case glslang::EOpConvDoubleToBool:
3642 zero = builder.makeDoubleConstant(0.0);
3643 zero = makeSmearedConstant(zero, vectorSize);
3644 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3645
3646 case glslang::EOpConvBoolToFloat:
3647 convOp = spv::OpSelect;
3648 zero = builder.makeFloatConstant(0.0);
3649 one = builder.makeFloatConstant(1.0);
3650 break;
3651 case glslang::EOpConvBoolToDouble:
3652 convOp = spv::OpSelect;
3653 zero = builder.makeDoubleConstant(0.0);
3654 one = builder.makeDoubleConstant(1.0);
3655 break;
3656 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003657 case glslang::EOpConvBoolToInt64:
3658 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3659 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003660 convOp = spv::OpSelect;
3661 break;
3662 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003663 case glslang::EOpConvBoolToUint64:
3664 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3665 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003666 convOp = spv::OpSelect;
3667 break;
3668
3669 case glslang::EOpConvIntToFloat:
3670 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003671 case glslang::EOpConvInt64ToFloat:
3672 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003673 convOp = spv::OpConvertSToF;
3674 break;
3675
3676 case glslang::EOpConvUintToFloat:
3677 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003678 case glslang::EOpConvUint64ToFloat:
3679 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003680 convOp = spv::OpConvertUToF;
3681 break;
3682
3683 case glslang::EOpConvDoubleToFloat:
3684 case glslang::EOpConvFloatToDouble:
3685 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003686 if (builder.isMatrixType(destType))
3687 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
3689
3690 case glslang::EOpConvFloatToInt:
3691 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003692 case glslang::EOpConvFloatToInt64:
3693 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003694 convOp = spv::OpConvertFToS;
3695 break;
3696
3697 case glslang::EOpConvUintToInt:
3698 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003699 case glslang::EOpConvUint64ToInt64:
3700 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003701 if (builder.isInSpecConstCodeGenMode()) {
3702 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003703 zero = (op == glslang::EOpConvUintToInt64 ||
3704 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003705 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003706 // Use OpIAdd, instead of OpBitcast to do the conversion when
3707 // generating for OpSpecConstantOp instruction.
3708 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3709 }
3710 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003711 convOp = spv::OpBitcast;
3712 break;
3713
3714 case glslang::EOpConvFloatToUint:
3715 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003716 case glslang::EOpConvFloatToUint64:
3717 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003718 convOp = spv::OpConvertFToU;
3719 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003720
3721 case glslang::EOpConvIntToInt64:
3722 case glslang::EOpConvInt64ToInt:
3723 convOp = spv::OpSConvert;
3724 break;
3725
3726 case glslang::EOpConvUintToUint64:
3727 case glslang::EOpConvUint64ToUint:
3728 convOp = spv::OpUConvert;
3729 break;
3730
3731 case glslang::EOpConvIntToUint64:
3732 case glslang::EOpConvInt64ToUint:
3733 case glslang::EOpConvUint64ToInt:
3734 case glslang::EOpConvUintToInt64:
3735 // OpSConvert/OpUConvert + OpBitCast
3736 switch (op) {
3737 case glslang::EOpConvIntToUint64:
3738 convOp = spv::OpSConvert;
3739 type = builder.makeIntType(64);
3740 break;
3741 case glslang::EOpConvInt64ToUint:
3742 convOp = spv::OpSConvert;
3743 type = builder.makeIntType(32);
3744 break;
3745 case glslang::EOpConvUint64ToInt:
3746 convOp = spv::OpUConvert;
3747 type = builder.makeUintType(32);
3748 break;
3749 case glslang::EOpConvUintToInt64:
3750 convOp = spv::OpUConvert;
3751 type = builder.makeUintType(64);
3752 break;
3753 default:
3754 assert(0);
3755 break;
3756 }
3757
3758 if (vectorSize > 0)
3759 type = builder.makeVectorType(type, vectorSize);
3760
3761 operand = builder.createUnaryOp(convOp, type, operand);
3762
3763 if (builder.isInSpecConstCodeGenMode()) {
3764 // Build zero scalar or vector for OpIAdd.
3765 zero = (op == glslang::EOpConvIntToUint64 ||
3766 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3767 zero = makeSmearedConstant(zero, vectorSize);
3768 // Use OpIAdd, instead of OpBitcast to do the conversion when
3769 // generating for OpSpecConstantOp instruction.
3770 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3771 }
3772 // For normal run-time conversion instruction, use OpBitcast.
3773 convOp = spv::OpBitcast;
3774 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003775 default:
3776 break;
3777 }
3778
3779 spv::Id result = 0;
3780 if (convOp == spv::OpNop)
3781 return result;
3782
3783 if (convOp == spv::OpSelect) {
3784 zero = makeSmearedConstant(zero, vectorSize);
3785 one = makeSmearedConstant(one, vectorSize);
3786 result = builder.createTriOp(convOp, destType, operand, one, zero);
3787 } else
3788 result = builder.createUnaryOp(convOp, destType, operand);
3789
John Kessenich32cfd492016-02-02 12:37:46 -07003790 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003791}
3792
3793spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3794{
3795 if (vectorSize == 0)
3796 return constant;
3797
3798 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3799 std::vector<spv::Id> components;
3800 for (int c = 0; c < vectorSize; ++c)
3801 components.push_back(constant);
3802 return builder.makeCompositeConstant(vectorTypeId, components);
3803}
3804
John Kessenich426394d2015-07-23 10:22:48 -06003805// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003806spv::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 -06003807{
3808 spv::Op opCode = spv::OpNop;
3809
3810 switch (op) {
3811 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003812 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003813 opCode = spv::OpAtomicIAdd;
3814 break;
3815 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003816 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003817 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003818 break;
3819 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003820 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003821 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003822 break;
3823 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003824 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003825 opCode = spv::OpAtomicAnd;
3826 break;
3827 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003828 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003829 opCode = spv::OpAtomicOr;
3830 break;
3831 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003832 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003833 opCode = spv::OpAtomicXor;
3834 break;
3835 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003836 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003837 opCode = spv::OpAtomicExchange;
3838 break;
3839 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003840 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003841 opCode = spv::OpAtomicCompareExchange;
3842 break;
3843 case glslang::EOpAtomicCounterIncrement:
3844 opCode = spv::OpAtomicIIncrement;
3845 break;
3846 case glslang::EOpAtomicCounterDecrement:
3847 opCode = spv::OpAtomicIDecrement;
3848 break;
3849 case glslang::EOpAtomicCounter:
3850 opCode = spv::OpAtomicLoad;
3851 break;
3852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003853 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003854 break;
3855 }
3856
3857 // Sort out the operands
3858 // - mapping from glslang -> SPV
3859 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003860 // - compare-exchange swaps the value and comparator
3861 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003862 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3863 auto opIt = operands.begin(); // walk the glslang operands
3864 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003865 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3866 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3867 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003868 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3869 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003870 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003871 spvAtomicOperands.push_back(*(opIt + 1));
3872 spvAtomicOperands.push_back(*opIt);
3873 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003874 }
John Kessenich426394d2015-07-23 10:22:48 -06003875
John Kessenich3e60a6f2015-09-14 22:45:16 -06003876 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003877 for (; opIt != operands.end(); ++opIt)
3878 spvAtomicOperands.push_back(*opIt);
3879
3880 return builder.createOp(opCode, typeId, spvAtomicOperands);
3881}
3882
John Kessenich91cef522016-05-05 16:45:40 -06003883// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003884spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003885{
Rex Xu9d93a232016-05-05 12:30:44 +08003886 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3887 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3888
John Kessenich91cef522016-05-05 16:45:40 -06003889 builder.addCapability(spv::CapabilityGroups);
3890
3891 std::vector<spv::Id> operands;
3892 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003893#ifdef AMD_EXTENSIONS
3894 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3895 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3896 operands.push_back(spv::GroupOperationReduce);
3897#endif
John Kessenich91cef522016-05-05 16:45:40 -06003898 operands.push_back(operand);
3899
3900 switch (op) {
3901 case glslang::EOpAnyInvocation:
3902 case glslang::EOpAllInvocations:
3903 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3904
3905 case glslang::EOpAllInvocationsEqual:
3906 {
3907 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3908 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3909
3910 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3911 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3912 }
Rex Xu9d93a232016-05-05 12:30:44 +08003913#ifdef AMD_EXTENSIONS
3914 case glslang::EOpMinInvocations:
3915 case glslang::EOpMaxInvocations:
3916 case glslang::EOpAddInvocations:
3917 {
3918 spv::Op spvOp = spv::OpNop;
3919 if (op == glslang::EOpMinInvocations) {
3920 if (isFloat)
3921 spvOp = spv::OpGroupFMin;
3922 else {
3923 if (isUnsigned)
3924 spvOp = spv::OpGroupUMin;
3925 else
3926 spvOp = spv::OpGroupSMin;
3927 }
3928 } else if (op == glslang::EOpMaxInvocations) {
3929 if (isFloat)
3930 spvOp = spv::OpGroupFMax;
3931 else {
3932 if (isUnsigned)
3933 spvOp = spv::OpGroupUMax;
3934 else
3935 spvOp = spv::OpGroupSMax;
3936 }
3937 } else {
3938 if (isFloat)
3939 spvOp = spv::OpGroupFAdd;
3940 else
3941 spvOp = spv::OpGroupIAdd;
3942 }
3943
3944 return builder.createOp(spvOp, typeId, operands);
3945 }
3946 case glslang::EOpMinInvocationsNonUniform:
3947 case glslang::EOpMaxInvocationsNonUniform:
3948 case glslang::EOpAddInvocationsNonUniform:
3949 {
3950 spv::Op spvOp = spv::OpNop;
3951 if (op == glslang::EOpMinInvocationsNonUniform) {
3952 if (isFloat)
3953 spvOp = spv::OpGroupFMinNonUniformAMD;
3954 else {
3955 if (isUnsigned)
3956 spvOp = spv::OpGroupUMinNonUniformAMD;
3957 else
3958 spvOp = spv::OpGroupSMinNonUniformAMD;
3959 }
3960 }
3961 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3962 if (isFloat)
3963 spvOp = spv::OpGroupFMaxNonUniformAMD;
3964 else {
3965 if (isUnsigned)
3966 spvOp = spv::OpGroupUMaxNonUniformAMD;
3967 else
3968 spvOp = spv::OpGroupSMaxNonUniformAMD;
3969 }
3970 }
3971 else {
3972 if (isFloat)
3973 spvOp = spv::OpGroupFAddNonUniformAMD;
3974 else
3975 spvOp = spv::OpGroupIAddNonUniformAMD;
3976 }
3977
3978 return builder.createOp(spvOp, typeId, operands);
3979 }
3980#endif
John Kessenich91cef522016-05-05 16:45:40 -06003981 default:
3982 logger->missingFunctionality("invocation operation");
3983 return spv::NoResult;
3984 }
3985}
3986
John Kessenich5e4b1242015-08-06 22:53:06 -06003987spv::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 -06003988{
Rex Xu8ff43de2016-04-22 16:51:45 +08003989 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003990 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3991
John Kessenich140f3df2015-06-26 16:58:36 -06003992 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003993 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003994 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003995 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003996 spv::Id typeId0 = 0;
3997 if (consumedOperands > 0)
3998 typeId0 = builder.getTypeId(operands[0]);
3999 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004000
4001 switch (op) {
4002 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004003 if (isFloat)
4004 libCall = spv::GLSLstd450FMin;
4005 else if (isUnsigned)
4006 libCall = spv::GLSLstd450UMin;
4007 else
4008 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004009 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004010 break;
4011 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004012 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004013 break;
4014 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004015 if (isFloat)
4016 libCall = spv::GLSLstd450FMax;
4017 else if (isUnsigned)
4018 libCall = spv::GLSLstd450UMax;
4019 else
4020 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004021 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004022 break;
4023 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004024 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004025 break;
4026 case glslang::EOpDot:
4027 opCode = spv::OpDot;
4028 break;
4029 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004030 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004031 break;
4032
4033 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004034 if (isFloat)
4035 libCall = spv::GLSLstd450FClamp;
4036 else if (isUnsigned)
4037 libCall = spv::GLSLstd450UClamp;
4038 else
4039 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004040 builder.promoteScalar(precision, operands.front(), operands[1]);
4041 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004042 break;
4043 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004044 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4045 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004046 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004047 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004048 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004049 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004050 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004051 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004052 break;
4053 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004054 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004055 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004056 break;
4057 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004059 builder.promoteScalar(precision, operands[0], operands[2]);
4060 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004061 break;
4062
4063 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004064 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004065 break;
4066 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 break;
4069 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
4072 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004073 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004074 break;
4075 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004076 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004078 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004079 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004080 libCall = spv::GLSLstd450InterpolateAtSample;
4081 break;
4082 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004083 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004084 libCall = spv::GLSLstd450InterpolateAtOffset;
4085 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004086 case glslang::EOpAddCarry:
4087 opCode = spv::OpIAddCarry;
4088 typeId = builder.makeStructResultType(typeId0, typeId0);
4089 consumedOperands = 2;
4090 break;
4091 case glslang::EOpSubBorrow:
4092 opCode = spv::OpISubBorrow;
4093 typeId = builder.makeStructResultType(typeId0, typeId0);
4094 consumedOperands = 2;
4095 break;
4096 case glslang::EOpUMulExtended:
4097 opCode = spv::OpUMulExtended;
4098 typeId = builder.makeStructResultType(typeId0, typeId0);
4099 consumedOperands = 2;
4100 break;
4101 case glslang::EOpIMulExtended:
4102 opCode = spv::OpSMulExtended;
4103 typeId = builder.makeStructResultType(typeId0, typeId0);
4104 consumedOperands = 2;
4105 break;
4106 case glslang::EOpBitfieldExtract:
4107 if (isUnsigned)
4108 opCode = spv::OpBitFieldUExtract;
4109 else
4110 opCode = spv::OpBitFieldSExtract;
4111 break;
4112 case glslang::EOpBitfieldInsert:
4113 opCode = spv::OpBitFieldInsert;
4114 break;
4115
4116 case glslang::EOpFma:
4117 libCall = spv::GLSLstd450Fma;
4118 break;
4119 case glslang::EOpFrexp:
4120 libCall = spv::GLSLstd450FrexpStruct;
4121 if (builder.getNumComponents(operands[0]) == 1)
4122 frexpIntType = builder.makeIntegerType(32, true);
4123 else
4124 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4125 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4126 consumedOperands = 1;
4127 break;
4128 case glslang::EOpLdexp:
4129 libCall = spv::GLSLstd450Ldexp;
4130 break;
4131
Rex Xu574ab042016-04-14 16:53:07 +08004132 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004133 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004134 libCall = spv::GLSLstd450Bad;
4135 break;
4136
Rex Xu9d93a232016-05-05 12:30:44 +08004137#ifdef AMD_EXTENSIONS
4138 case glslang::EOpSwizzleInvocations:
4139 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4140 libCall = spv::SwizzleInvocationsAMD;
4141 break;
4142 case glslang::EOpSwizzleInvocationsMasked:
4143 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4144 libCall = spv::SwizzleInvocationsMaskedAMD;
4145 break;
4146 case glslang::EOpWriteInvocation:
4147 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4148 libCall = spv::WriteInvocationAMD;
4149 break;
4150
4151 case glslang::EOpMin3:
4152 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4153 if (isFloat)
4154 libCall = spv::FMin3AMD;
4155 else {
4156 if (isUnsigned)
4157 libCall = spv::UMin3AMD;
4158 else
4159 libCall = spv::SMin3AMD;
4160 }
4161 break;
4162 case glslang::EOpMax3:
4163 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4164 if (isFloat)
4165 libCall = spv::FMax3AMD;
4166 else {
4167 if (isUnsigned)
4168 libCall = spv::UMax3AMD;
4169 else
4170 libCall = spv::SMax3AMD;
4171 }
4172 break;
4173 case glslang::EOpMid3:
4174 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4175 if (isFloat)
4176 libCall = spv::FMid3AMD;
4177 else {
4178 if (isUnsigned)
4179 libCall = spv::UMid3AMD;
4180 else
4181 libCall = spv::SMid3AMD;
4182 }
4183 break;
4184
4185 case glslang::EOpInterpolateAtVertex:
4186 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4187 libCall = spv::InterpolateAtVertexAMD;
4188 break;
4189#endif
4190
John Kessenich140f3df2015-06-26 16:58:36 -06004191 default:
4192 return 0;
4193 }
4194
4195 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004196 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004197 // Use an extended instruction from the standard library.
4198 // Construct the call arguments, without modifying the original operands vector.
4199 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4200 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004201 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004202 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004203 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004204 case 0:
4205 // should all be handled by visitAggregate and createNoArgOperation
4206 assert(0);
4207 return 0;
4208 case 1:
4209 // should all be handled by createUnaryOperation
4210 assert(0);
4211 return 0;
4212 case 2:
4213 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4214 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004215 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004216 // anything 3 or over doesn't have l-value operands, so all should be consumed
4217 assert(consumedOperands == operands.size());
4218 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004219 break;
4220 }
4221 }
4222
John Kessenich55e7d112015-11-15 21:33:39 -07004223 // Decode the return types that were structures
4224 switch (op) {
4225 case glslang::EOpAddCarry:
4226 case glslang::EOpSubBorrow:
4227 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4228 id = builder.createCompositeExtract(id, typeId0, 0);
4229 break;
4230 case glslang::EOpUMulExtended:
4231 case glslang::EOpIMulExtended:
4232 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4233 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4234 break;
4235 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004236 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004237 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4238 id = builder.createCompositeExtract(id, typeId0, 0);
4239 break;
4240 default:
4241 break;
4242 }
4243
John Kessenich32cfd492016-02-02 12:37:46 -07004244 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004245}
4246
Rex Xu9d93a232016-05-05 12:30:44 +08004247// Intrinsics with no arguments (or no return value, and no precision).
4248spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004249{
4250 // TODO: get the barrier operands correct
4251
4252 switch (op) {
4253 case glslang::EOpEmitVertex:
4254 builder.createNoResultOp(spv::OpEmitVertex);
4255 return 0;
4256 case glslang::EOpEndPrimitive:
4257 builder.createNoResultOp(spv::OpEndPrimitive);
4258 return 0;
4259 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004260 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004261 return 0;
4262 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004263 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004264 return 0;
4265 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004266 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004267 return 0;
4268 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004269 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004270 return 0;
4271 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004272 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004273 return 0;
4274 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004275 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004276 return 0;
4277 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004278 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004279 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004280 case glslang::EOpAllMemoryBarrierWithGroupSync:
4281 // Control barrier with non-"None" semantic is also a memory barrier.
4282 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4283 return 0;
4284 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4285 // Control barrier with non-"None" semantic is also a memory barrier.
4286 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4287 return 0;
4288 case glslang::EOpWorkgroupMemoryBarrier:
4289 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4290 return 0;
4291 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4292 // Control barrier with non-"None" semantic is also a memory barrier.
4293 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4294 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004295#ifdef AMD_EXTENSIONS
4296 case glslang::EOpTime:
4297 {
4298 std::vector<spv::Id> args; // Dummy arguments
4299 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4300 return builder.setPrecision(id, precision);
4301 }
4302#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004303 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004304 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004305 return 0;
4306 }
4307}
4308
4309spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4310{
John Kessenich2f273362015-07-18 22:34:27 -06004311 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004312 spv::Id id;
4313 if (symbolValues.end() != iter) {
4314 id = iter->second;
4315 return id;
4316 }
4317
4318 // it was not found, create it
4319 id = createSpvVariable(symbol);
4320 symbolValues[symbol->getId()] = id;
4321
Rex Xuc884b4a2016-06-29 15:03:44 +08004322 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004323 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004324 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004325 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004326 if (symbol->getType().getQualifier().hasSpecConstantId())
4327 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004328 if (symbol->getQualifier().hasIndex())
4329 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4330 if (symbol->getQualifier().hasComponent())
4331 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4332 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004333 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004334 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004336 if (symbol->getQualifier().hasXfbBuffer())
4337 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4338 if (symbol->getQualifier().hasXfbOffset())
4339 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4340 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004341 // atomic counters use this:
4342 if (symbol->getQualifier().hasOffset())
4343 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004344 }
4345
scygan2c864272016-05-18 18:09:17 +02004346 if (symbol->getQualifier().hasLocation())
4347 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004348 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004349 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004350 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004351 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004352 }
John Kessenich140f3df2015-06-26 16:58:36 -06004353 if (symbol->getQualifier().hasSet())
4354 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004355 else if (IsDescriptorResource(symbol->getType())) {
4356 // default to 0
4357 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4358 }
John Kessenich140f3df2015-06-26 16:58:36 -06004359 if (symbol->getQualifier().hasBinding())
4360 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004361 if (symbol->getQualifier().hasAttachment())
4362 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004363 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004364 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004365 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004367 if (symbol->getQualifier().hasXfbBuffer())
4368 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4369 }
4370
Rex Xu1da878f2016-02-21 20:59:01 +08004371 if (symbol->getType().isImage()) {
4372 std::vector<spv::Decoration> memory;
4373 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4374 for (unsigned int i = 0; i < memory.size(); ++i)
4375 addDecoration(id, memory[i]);
4376 }
4377
John Kessenich140f3df2015-06-26 16:58:36 -06004378 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004379 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004380 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004381 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004382
John Kessenich140f3df2015-06-26 16:58:36 -06004383 return id;
4384}
4385
John Kessenich55e7d112015-11-15 21:33:39 -07004386// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004387void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4388{
John Kessenich4016e382016-07-15 11:53:56 -06004389 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004390 builder.addDecoration(id, dec);
4391}
4392
John Kessenich55e7d112015-11-15 21:33:39 -07004393// If 'dec' is valid, add a one-operand decoration to an object
4394void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4395{
John Kessenich4016e382016-07-15 11:53:56 -06004396 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004397 builder.addDecoration(id, dec, value);
4398}
4399
4400// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004401void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4402{
John Kessenich4016e382016-07-15 11:53:56 -06004403 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004404 builder.addMemberDecoration(id, (unsigned)member, dec);
4405}
4406
John Kessenich92187592016-02-01 13:45:25 -07004407// If 'dec' is valid, add a one-operand decoration to a struct member
4408void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4409{
John Kessenich4016e382016-07-15 11:53:56 -06004410 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004411 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4412}
4413
John Kessenich55e7d112015-11-15 21:33:39 -07004414// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004415// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004416//
4417// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4418//
4419// Recursively walk the nodes. The nodes form a tree whose leaves are
4420// regular constants, which themselves are trees that createSpvConstant()
4421// recursively walks. So, this function walks the "top" of the tree:
4422// - emit specialization constant-building instructions for specConstant
4423// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004424spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004425{
John Kessenich7cc0e282016-03-20 00:46:02 -06004426 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004427
qining4f4bb812016-04-03 23:55:17 -04004428 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004429 if (! node.getQualifier().specConstant) {
4430 // hand off to the non-spec-constant path
4431 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4432 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004433 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004434 nextConst, false);
4435 }
4436
4437 // We now know we have a specialization constant to build
4438
John Kessenichd94c0032016-05-30 19:29:40 -06004439 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004440 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4441 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4442 std::vector<spv::Id> dimConstId;
4443 for (int dim = 0; dim < 3; ++dim) {
4444 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4445 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4446 if (specConst)
4447 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4448 }
4449 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4450 }
4451
4452 // An AST node labelled as specialization constant should be a symbol node.
4453 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4454 if (auto* sn = node.getAsSymbolNode()) {
4455 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004456 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4457 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4458 // will set the builder into spec constant op instruction generating mode.
4459 sub_tree->traverse(this);
4460 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004461 } else if (auto* const_union_array = &sn->getConstArray()){
4462 int nextConst = 0;
4463 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004464 }
4465 }
qining4f4bb812016-04-03 23:55:17 -04004466
4467 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4468 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004469 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004470 exit(1);
4471 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004472}
4473
John Kessenich140f3df2015-06-26 16:58:36 -06004474// Use 'consts' as the flattened glslang source of scalar constants to recursively
4475// build the aggregate SPIR-V constant.
4476//
4477// If there are not enough elements present in 'consts', 0 will be substituted;
4478// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4479//
qining08408382016-03-21 09:51:37 -04004480spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004481{
4482 // vector of constants for SPIR-V
4483 std::vector<spv::Id> spvConsts;
4484
4485 // Type is used for struct and array constants
4486 spv::Id typeId = convertGlslangToSpvType(glslangType);
4487
4488 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004489 glslang::TType elementType(glslangType, 0);
4490 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004491 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004492 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004493 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004494 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004495 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004496 } else if (glslangType.getStruct()) {
4497 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4498 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004499 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004500 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004501 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4502 bool zero = nextConst >= consts.size();
4503 switch (glslangType.getBasicType()) {
4504 case glslang::EbtInt:
4505 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4506 break;
4507 case glslang::EbtUint:
4508 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4509 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004510 case glslang::EbtInt64:
4511 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4512 break;
4513 case glslang::EbtUint64:
4514 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4515 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004516 case glslang::EbtFloat:
4517 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4518 break;
4519 case glslang::EbtDouble:
4520 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4521 break;
4522 case glslang::EbtBool:
4523 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4524 break;
4525 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004526 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004527 break;
4528 }
4529 ++nextConst;
4530 }
4531 } else {
4532 // we have a non-aggregate (scalar) constant
4533 bool zero = nextConst >= consts.size();
4534 spv::Id scalar = 0;
4535 switch (glslangType.getBasicType()) {
4536 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004537 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004538 break;
4539 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004540 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004541 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004542 case glslang::EbtInt64:
4543 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4544 break;
4545 case glslang::EbtUint64:
4546 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4547 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004548 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004549 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004550 break;
4551 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004552 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004553 break;
4554 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004555 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004556 break;
4557 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004558 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004559 break;
4560 }
4561 ++nextConst;
4562 return scalar;
4563 }
4564
4565 return builder.makeCompositeConstant(typeId, spvConsts);
4566}
4567
John Kessenich7c1aa102015-10-15 13:29:11 -06004568// Return true if the node is a constant or symbol whose reading has no
4569// non-trivial observable cost or effect.
4570bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4571{
4572 // don't know what this is
4573 if (node == nullptr)
4574 return false;
4575
4576 // a constant is safe
4577 if (node->getAsConstantUnion() != nullptr)
4578 return true;
4579
4580 // not a symbol means non-trivial
4581 if (node->getAsSymbolNode() == nullptr)
4582 return false;
4583
4584 // a symbol, depends on what's being read
4585 switch (node->getType().getQualifier().storage) {
4586 case glslang::EvqTemporary:
4587 case glslang::EvqGlobal:
4588 case glslang::EvqIn:
4589 case glslang::EvqInOut:
4590 case glslang::EvqConst:
4591 case glslang::EvqConstReadOnly:
4592 case glslang::EvqUniform:
4593 return true;
4594 default:
4595 return false;
4596 }
qining25262b32016-05-06 17:25:16 -04004597}
John Kessenich7c1aa102015-10-15 13:29:11 -06004598
4599// A node is trivial if it is a single operation with no side effects.
4600// Error on the side of saying non-trivial.
4601// Return true if trivial.
4602bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4603{
4604 if (node == nullptr)
4605 return false;
4606
4607 // symbols and constants are trivial
4608 if (isTrivialLeaf(node))
4609 return true;
4610
4611 // otherwise, it needs to be a simple operation or one or two leaf nodes
4612
4613 // not a simple operation
4614 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4615 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4616 if (binaryNode == nullptr && unaryNode == nullptr)
4617 return false;
4618
4619 // not on leaf nodes
4620 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4621 return false;
4622
4623 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4624 return false;
4625 }
4626
4627 switch (node->getAsOperator()->getOp()) {
4628 case glslang::EOpLogicalNot:
4629 case glslang::EOpConvIntToBool:
4630 case glslang::EOpConvUintToBool:
4631 case glslang::EOpConvFloatToBool:
4632 case glslang::EOpConvDoubleToBool:
4633 case glslang::EOpEqual:
4634 case glslang::EOpNotEqual:
4635 case glslang::EOpLessThan:
4636 case glslang::EOpGreaterThan:
4637 case glslang::EOpLessThanEqual:
4638 case glslang::EOpGreaterThanEqual:
4639 case glslang::EOpIndexDirect:
4640 case glslang::EOpIndexDirectStruct:
4641 case glslang::EOpLogicalXor:
4642 case glslang::EOpAny:
4643 case glslang::EOpAll:
4644 return true;
4645 default:
4646 return false;
4647 }
4648}
4649
4650// Emit short-circuiting code, where 'right' is never evaluated unless
4651// the left side is true (for &&) or false (for ||).
4652spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4653{
4654 spv::Id boolTypeId = builder.makeBoolType();
4655
4656 // emit left operand
4657 builder.clearAccessChain();
4658 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004659 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004660
4661 // Operands to accumulate OpPhi operands
4662 std::vector<spv::Id> phiOperands;
4663 // accumulate left operand's phi information
4664 phiOperands.push_back(leftId);
4665 phiOperands.push_back(builder.getBuildPoint()->getId());
4666
4667 // Make the two kinds of operation symmetric with a "!"
4668 // || => emit "if (! left) result = right"
4669 // && => emit "if ( left) result = right"
4670 //
4671 // TODO: this runtime "not" for || could be avoided by adding functionality
4672 // to 'builder' to have an "else" without an "then"
4673 if (op == glslang::EOpLogicalOr)
4674 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4675
4676 // make an "if" based on the left value
4677 spv::Builder::If ifBuilder(leftId, builder);
4678
4679 // emit right operand as the "then" part of the "if"
4680 builder.clearAccessChain();
4681 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004682 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004683
4684 // accumulate left operand's phi information
4685 phiOperands.push_back(rightId);
4686 phiOperands.push_back(builder.getBuildPoint()->getId());
4687
4688 // finish the "if"
4689 ifBuilder.makeEndIf();
4690
4691 // phi together the two results
4692 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4693}
4694
Rex Xu9d93a232016-05-05 12:30:44 +08004695// Return type Id of the imported set of extended instructions corresponds to the name.
4696// Import this set if it has not been imported yet.
4697spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4698{
4699 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4700 return extBuiltinMap[name];
4701 else {
4702 builder.addExtensions(name);
4703 spv::Id extBuiltins = builder.import(name);
4704 extBuiltinMap[name] = extBuiltins;
4705 return extBuiltins;
4706 }
4707}
4708
John Kessenich140f3df2015-06-26 16:58:36 -06004709}; // end anonymous namespace
4710
4711namespace glslang {
4712
John Kessenich68d78fd2015-07-12 19:28:10 -06004713void GetSpirvVersion(std::string& version)
4714{
John Kessenich9e55f632015-07-15 10:03:39 -06004715 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004716 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004717 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004718 version = buf;
4719}
4720
John Kessenich140f3df2015-06-26 16:58:36 -06004721// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004722void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004723{
4724 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004725 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004726 for (int i = 0; i < (int)spirv.size(); ++i) {
4727 unsigned int word = spirv[i];
4728 out.write((const char*)&word, 4);
4729 }
4730 out.close();
4731}
4732
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004733// Write SPIR-V out to a text file with 32-bit hexadecimal words
4734void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4735{
4736 std::ofstream out;
4737 out.open(baseName, std::ios::binary | std::ios::out);
4738 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4739 const int WORDS_PER_LINE = 8;
4740 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4741 out << "\t";
4742 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4743 const unsigned int word = spirv[i + j];
4744 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4745 if (i + j + 1 < (int)spirv.size()) {
4746 out << ",";
4747 }
4748 }
4749 out << std::endl;
4750 }
4751 out.close();
4752}
4753
John Kessenich140f3df2015-06-26 16:58:36 -06004754//
4755// Set up the glslang traversal
4756//
4757void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4758{
Lei Zhang17535f72016-05-04 15:55:59 -04004759 spv::SpvBuildLogger logger;
4760 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004761}
4762
Lei Zhang17535f72016-05-04 15:55:59 -04004763void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004764{
John Kessenich140f3df2015-06-26 16:58:36 -06004765 TIntermNode* root = intermediate.getTreeRoot();
4766
4767 if (root == 0)
4768 return;
4769
4770 glslang::GetThreadPoolAllocator().push();
4771
Lei Zhang17535f72016-05-04 15:55:59 -04004772 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004773
4774 root->traverse(&it);
4775
4776 it.dumpSpv(spirv);
4777
4778 glslang::GetThreadPoolAllocator().pop();
4779}
4780
4781}; // end namespace glslang