blob: 9f272ee5e5694a44cc050372fbf2bb4c339d54b8 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
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//
John Kessenich927608b2017-01-06 12:34:14 -070023// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060035
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 {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600132 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
133 glslang::TLayoutPacking, const glslang::TQualifier&);
134 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
135 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700136 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700137 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800138 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600139 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700140 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700141 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
142 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 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 +0100144 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600145
John Kessenich6fccb3c2016-09-19 16:01:41 -0600146 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 void makeFunctions(const glslang::TIntermSequence&);
148 void makeGlobalInitializers(const glslang::TIntermSequence&);
149 void visitFunctions(const glslang::TIntermSequence&);
150 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800151 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600152 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
153 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
155
qining25262b32016-05-06 17:25:16 -0400156 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);
157 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
158 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800159 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800160 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 -0600161 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800163 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600165 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 +0800166 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
168 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700169 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400172 spv::Id createSpvConstant(const glslang::TIntermTyped&);
173 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600174 bool isTrivialLeaf(const glslang::TIntermTyped* node);
175 bool isTrivial(const glslang::TIntermTyped* node);
176 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800177 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600178
179 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600180 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700181 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600182 int sequenceDepth;
183
Lei Zhang17535f72016-05-04 15:55:59 -0400184 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400185
John Kessenich140f3df2015-06-26 16:58:36 -0600186 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
187 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700188 bool inEntryPoint;
189 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700190 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 -0700191 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600192 const glslang::TIntermediate* glslangIntermediate;
193 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800194 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600195
John Kessenich2f273362015-07-18 22:34:27 -0600196 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600197 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600198 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700199 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600200 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 -0600201 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600202};
203
204//
205// Helper functions for translating glslang representations to SPIR-V enumerants.
206//
207
208// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700209spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600210{
John Kessenich66e2faf2016-03-12 18:34:36 -0700211 switch (source) {
212 case glslang::EShSourceGlsl:
213 switch (profile) {
214 case ENoProfile:
215 case ECoreProfile:
216 case ECompatibilityProfile:
217 return spv::SourceLanguageGLSL;
218 case EEsProfile:
219 return spv::SourceLanguageESSL;
220 default:
221 return spv::SourceLanguageUnknown;
222 }
223 case glslang::EShSourceHlsl:
John Kessenich927608b2017-01-06 12:34:14 -0700224 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400225 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 } else {
266 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
270 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::StorageClassFunction;
274 }
275 }
276}
277
278// Translate glslang sampler type to SPIR-V dimensionality.
279spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
280{
281 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700282 case glslang::Esd1D: return spv::Dim1D;
283 case glslang::Esd2D: return spv::Dim2D;
284 case glslang::Esd3D: return spv::Dim3D;
285 case glslang::EsdCube: return spv::DimCube;
286 case glslang::EsdRect: return spv::DimRect;
287 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700288 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::Dim2D;
292 }
293}
294
John Kessenichf6640762016-08-01 19:44:00 -0600295// Translate glslang precision to SPIR-V precision decorations.
296spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
John Kessenichf6640762016-08-01 19:44:00 -0600298 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700299 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600300 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600301 default:
302 return spv::NoPrecision;
303 }
304}
305
John Kessenichf6640762016-08-01 19:44:00 -0600306// Translate glslang type to SPIR-V precision decorations.
307spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
308{
309 return TranslatePrecisionDecoration(type.getQualifier().precision);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V block decorations.
313spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
314{
315 if (type.getBasicType() == glslang::EbtBlock) {
316 switch (type.getQualifier().storage) {
317 case glslang::EvqUniform: return spv::DecorationBlock;
318 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
319 case glslang::EvqVaryingIn: return spv::DecorationBlock;
320 case glslang::EvqVaryingOut: return spv::DecorationBlock;
321 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600323 break;
324 }
325 }
326
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328}
329
Rex Xu1da878f2016-02-21 20:59:01 +0800330// Translate glslang type to SPIR-V memory decorations.
331void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
332{
333 if (qualifier.coherent)
334 memory.push_back(spv::DecorationCoherent);
335 if (qualifier.volatil)
336 memory.push_back(spv::DecorationVolatile);
337 if (qualifier.restrict)
338 memory.push_back(spv::DecorationRestrict);
339 if (qualifier.readonly)
340 memory.push_back(spv::DecorationNonWritable);
341 if (qualifier.writeonly)
342 memory.push_back(spv::DecorationNonReadable);
343}
344
John Kessenich140f3df2015-06-26 16:58:36 -0600345// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700346spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
348 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElmRowMajor:
351 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 default:
355 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 } else {
359 switch (type.getBasicType()) {
360 default:
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 break;
363 case glslang::EbtBlock:
364 switch (type.getQualifier().storage) {
365 case glslang::EvqUniform:
366 case glslang::EvqBuffer:
367 switch (type.getQualifier().layoutPacking) {
368 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 case glslang::EvqVaryingIn:
374 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 }
382 }
383}
384
385// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600386// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700387// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800388spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
Rex Xubbceed72016-05-21 09:40:44 +0800390 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800393 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800397#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800398 else if (qualifier.explicitInterp) {
399 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800400 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800401 }
Rex Xu9d93a232016-05-05 12:30:44 +0800402#endif
Rex Xubbceed72016-05-21 09:40:44 +0800403 else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800405}
406
407// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800409// should be applied.
410spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
411{
412 if (qualifier.patch)
413 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700416 else if (qualifier.sample) {
417 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700419 } else
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421}
422
John Kessenich92187592016-02-01 13:45:25 -0700423// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600425{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationInvariant;
428 else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
qining9220dbb2016-05-04 17:34:38 -0400432// If glslang type is noContraction, return SPIR-V NoContraction decoration.
433spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
434{
435 if (qualifier.noContraction)
436 return spv::DecorationNoContraction;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400439}
440
David Netoa901ffe2016-06-08 14:11:40 +0100441// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
442// associated capabilities when required. For some built-in variables, a capability
443// is generated only when using the variable in an executable instruction, but not when
444// just declaring a struct member variable with it. This is true for PointSize,
445// ClipDistance, and CullDistance.
446spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
448 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700449 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600450 // Defer adding the capability until the built-in is actually used.
451 if (! memberDeclaration) {
452 switch (glslangIntermediate->getStage()) {
453 case EShLangGeometry:
454 builder.addCapability(spv::CapabilityGeometryPointSize);
455 break;
456 case EShLangTessControl:
457 case EShLangTessEvaluation:
458 builder.addCapability(spv::CapabilityTessellationPointSize);
459 break;
460 default:
461 break;
462 }
John Kessenich92187592016-02-01 13:45:25 -0700463 }
464 return spv::BuiltInPointSize;
465
John Kessenichebb50532016-05-16 19:22:05 -0600466 // These *Distance capabilities logically belong here, but if the member is declared and
467 // then never used, consumers of SPIR-V prefer the capability not be declared.
468 // They are now generated when used, rather than here when declared.
469 // Potentially, the specification should be more clear what the minimum
470 // use needed is to trigger the capability.
471 //
John Kessenich92187592016-02-01 13:45:25 -0700472 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInClipDistance;
476
477 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInCullDistance;
481
482 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
John Kessenich92187592016-02-01 13:45:25 -0700495 return spv::BuiltInViewportIndex;
496
John Kessenich5e801132016-02-15 11:09:46 -0700497 case glslang::EbvSampleId:
498 builder.addCapability(spv::CapabilitySampleRateShading);
499 return spv::BuiltInSampleId;
500
501 case glslang::EbvSamplePosition:
502 builder.addCapability(spv::CapabilitySampleRateShading);
503 return spv::BuiltInSamplePosition;
504
505 case glslang::EbvSampleMask:
506 builder.addCapability(spv::CapabilitySampleRateShading);
507 return spv::BuiltInSampleMask;
508
John Kessenich78a45572016-07-08 14:05:15 -0600509 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800510 if (!memberDeclaration) {
511 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800512#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800513 if (glslangIntermediate->getStage() == EShLangVertex ||
514 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800515 glslangIntermediate->getStage() == EShLangTessEvaluation) {
516
chaoc771d89f2017-01-13 01:10:53 -0800517 builder.addExtension(spv::E_SPV_NV_viewport_array2);
518 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
519 }
chaoc771d89f2017-01-13 01:10:53 -0800520#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800521 }
522
John Kessenich78a45572016-07-08 14:05:15 -0600523 return spv::BuiltInLayer;
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvVertexId: return spv::BuiltInVertexId;
527 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700528 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
529 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800530
John Kessenichda581a22015-10-14 14:10:30 -0600531 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800532 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
533 builder.addCapability(spv::CapabilityDrawParameters);
534 return spv::BuiltInBaseVertex;
535
John Kessenichda581a22015-10-14 14:10:30 -0600536 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800537 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
538 builder.addCapability(spv::CapabilityDrawParameters);
539 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200540
John Kessenichda581a22015-10-14 14:10:30 -0600541 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800542 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
543 builder.addCapability(spv::CapabilityDrawParameters);
544 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200545
546 case glslang::EbvPrimitiveId:
547 if (glslangIntermediate->getStage() == EShLangFragment)
548 builder.addCapability(spv::CapabilityGeometry);
549 return spv::BuiltInPrimitiveId;
550
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
553 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
554 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
555 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
556 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
557 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
558 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600559 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
560 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
561 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
562 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
563 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
564 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
565 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
566 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupSize;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLocalInvocationId;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupEqMaskKHR;
582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupGeMaskKHR;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupGtMaskKHR;
592
Rex Xu574ab042016-04-14 16:53:07 +0800593 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800594 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
595 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
596 return spv::BuiltInSubgroupLeMaskKHR;
597
Rex Xu574ab042016-04-14 16:53:07 +0800598 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800599 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
600 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
601 return spv::BuiltInSubgroupLtMaskKHR;
602
Rex Xu9d93a232016-05-05 12:30:44 +0800603#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800604 case glslang::EbvBaryCoordNoPersp:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordNoPerspAMD;
607
608 case glslang::EbvBaryCoordNoPerspCentroid:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
611
612 case glslang::EbvBaryCoordNoPerspSample:
613 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
614 return spv::BuiltInBaryCoordNoPerspSampleAMD;
615
616 case glslang::EbvBaryCoordSmooth:
617 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
618 return spv::BuiltInBaryCoordSmoothAMD;
619
620 case glslang::EbvBaryCoordSmoothCentroid:
621 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
622 return spv::BuiltInBaryCoordSmoothCentroidAMD;
623
624 case glslang::EbvBaryCoordSmoothSample:
625 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
626 return spv::BuiltInBaryCoordSmoothSampleAMD;
627
628 case glslang::EbvBaryCoordPullModel:
629 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
630 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800631#endif
chaoc771d89f2017-01-13 01:10:53 -0800632
John Kessenich6c8aaac2017-02-27 01:20:51 -0700633 case glslang::EbvDeviceIndex:
634 builder.addExtension(spv::E_SPV_KHR_device_group);
635 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700636 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700637
638 case glslang::EbvViewIndex:
639 builder.addExtension(spv::E_SPV_KHR_multiview);
640 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700641 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700642
chaoc771d89f2017-01-13 01:10:53 -0800643#ifdef NV_EXTENSIONS
644 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NV_viewport_array2);
647 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
648 }
chaoc771d89f2017-01-13 01:10:53 -0800649 return spv::BuiltInViewportMaskNV;
650 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800651 if (!memberDeclaration) {
652 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
653 builder.addCapability(spv::CapabilityShaderStereoViewNV);
654 }
chaoc771d89f2017-01-13 01:10:53 -0800655 return spv::BuiltInSecondaryPositionNV;
656 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800657 if (!memberDeclaration) {
658 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
659 builder.addCapability(spv::CapabilityShaderStereoViewNV);
660 }
chaoc771d89f2017-01-13 01:10:53 -0800661 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800662 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800663 if (!memberDeclaration) {
664 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
665 builder.addCapability(spv::CapabilityPerViewAttributesNV);
666 }
chaocdf3956c2017-02-14 14:52:34 -0800667 return spv::BuiltInPositionPerViewNV;
668 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800669 if (!memberDeclaration) {
670 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
671 builder.addCapability(spv::CapabilityPerViewAttributesNV);
672 }
chaocdf3956c2017-02-14 14:52:34 -0800673 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800674#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800675 default:
676 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600677 }
678}
679
Rex Xufc618912015-09-09 16:42:49 +0800680// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700681spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800682{
683 assert(type.getBasicType() == glslang::EbtSampler);
684
John Kessenich5d0fa972016-02-15 11:57:00 -0700685 // Check for capabilities
686 switch (type.getQualifier().layoutFormat) {
687 case glslang::ElfRg32f:
688 case glslang::ElfRg16f:
689 case glslang::ElfR11fG11fB10f:
690 case glslang::ElfR16f:
691 case glslang::ElfRgba16:
692 case glslang::ElfRgb10A2:
693 case glslang::ElfRg16:
694 case glslang::ElfRg8:
695 case glslang::ElfR16:
696 case glslang::ElfR8:
697 case glslang::ElfRgba16Snorm:
698 case glslang::ElfRg16Snorm:
699 case glslang::ElfRg8Snorm:
700 case glslang::ElfR16Snorm:
701 case glslang::ElfR8Snorm:
702
703 case glslang::ElfRg32i:
704 case glslang::ElfRg16i:
705 case glslang::ElfRg8i:
706 case glslang::ElfR16i:
707 case glslang::ElfR8i:
708
709 case glslang::ElfRgb10a2ui:
710 case glslang::ElfRg32ui:
711 case glslang::ElfRg16ui:
712 case glslang::ElfRg8ui:
713 case glslang::ElfR16ui:
714 case glslang::ElfR8ui:
715 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
716 break;
717
718 default:
719 break;
720 }
721
722 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800723 switch (type.getQualifier().layoutFormat) {
724 case glslang::ElfNone: return spv::ImageFormatUnknown;
725 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
726 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
727 case glslang::ElfR32f: return spv::ImageFormatR32f;
728 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
729 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
730 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
731 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
732 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
733 case glslang::ElfR16f: return spv::ImageFormatR16f;
734 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
735 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
736 case glslang::ElfRg16: return spv::ImageFormatRg16;
737 case glslang::ElfRg8: return spv::ImageFormatRg8;
738 case glslang::ElfR16: return spv::ImageFormatR16;
739 case glslang::ElfR8: return spv::ImageFormatR8;
740 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
741 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
742 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
743 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
744 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
745 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
746 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
747 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
748 case glslang::ElfR32i: return spv::ImageFormatR32i;
749 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
750 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
751 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
752 case glslang::ElfR16i: return spv::ImageFormatR16i;
753 case glslang::ElfR8i: return spv::ImageFormatR8i;
754 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
755 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
756 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
757 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
758 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
759 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
760 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
761 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
762 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
763 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600764 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800765 }
766}
767
qining25262b32016-05-06 17:25:16 -0400768// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700769// descriptor set.
770bool IsDescriptorResource(const glslang::TType& type)
771{
John Kessenichf7497e22016-03-08 21:36:22 -0700772 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700773 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700774 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700775
776 // non block...
777 // basically samplerXXX/subpass/sampler/texture are all included
778 // if they are the global-scope-class, not the function parameter
779 // (or local, if they ever exist) class.
780 if (type.getBasicType() == glslang::EbtSampler)
781 return type.getQualifier().isUniformOrBuffer();
782
783 // None of the above.
784 return false;
785}
786
John Kesseniche0b6cad2015-12-24 10:30:13 -0700787void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
788{
789 if (child.layoutMatrix == glslang::ElmNone)
790 child.layoutMatrix = parent.layoutMatrix;
791
792 if (parent.invariant)
793 child.invariant = true;
794 if (parent.nopersp)
795 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800796#ifdef AMD_EXTENSIONS
797 if (parent.explicitInterp)
798 child.explicitInterp = true;
799#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700800 if (parent.flat)
801 child.flat = true;
802 if (parent.centroid)
803 child.centroid = true;
804 if (parent.patch)
805 child.patch = true;
806 if (parent.sample)
807 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800808 if (parent.coherent)
809 child.coherent = true;
810 if (parent.volatil)
811 child.volatil = true;
812 if (parent.restrict)
813 child.restrict = true;
814 if (parent.readonly)
815 child.readonly = true;
816 if (parent.writeonly)
817 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700818}
819
John Kessenichf2b7f332016-09-01 17:05:23 -0600820bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700821{
John Kessenich7b9fa252016-01-21 18:56:57 -0700822 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600823 // - struct members might inherit from a struct declaration
824 // (note that non-block structs don't explicitly inherit,
825 // only implicitly, meaning no decoration involved)
826 // - affect decorations on the struct members
827 // (note smooth does not, and expecting something like volatile
828 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700829 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600830 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831}
832
John Kessenich140f3df2015-06-26 16:58:36 -0600833//
834// Implement the TGlslangToSpvTraverser class.
835//
836
Lei Zhang17535f72016-05-04 15:55:59 -0400837TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600838 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
839 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400840 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700841 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600842 glslangIntermediate(glslangIntermediate)
843{
844 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
845
846 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700847 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600848 stdBuiltins = builder.import("GLSL.std.450");
849 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600850 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
851 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600852
853 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600854 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
855 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600856 builder.addSourceExtension(it->c_str());
857
858 // Add the top-level modes for this shader.
859
John Kessenich92187592016-02-01 13:45:25 -0700860 if (glslangIntermediate->getXfbMode()) {
861 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700863 }
John Kessenich140f3df2015-06-26 16:58:36 -0600864
865 unsigned int mode;
866 switch (glslangIntermediate->getStage()) {
867 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 break;
870
871 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600872 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600873 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
874 break;
875
876 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600877 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600878 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700879 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
880 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
881 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600882 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600883 }
John Kessenich4016e382016-07-15 11:53:56 -0600884 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600885 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
886
John Kesseniche6903322015-10-13 16:29:02 -0600887 switch (glslangIntermediate->getVertexSpacing()) {
888 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
889 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
890 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600891 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600892 }
John Kessenich4016e382016-07-15 11:53:56 -0600893 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600894 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
895
896 switch (glslangIntermediate->getVertexOrder()) {
897 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
898 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600899 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600900 }
John Kessenich4016e382016-07-15 11:53:56 -0600901 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600902 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
903
904 if (glslangIntermediate->getPointMode())
905 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600906 break;
907
908 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600909 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600910 switch (glslangIntermediate->getInputPrimitive()) {
911 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
912 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
913 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700914 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600915 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600916 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600917 }
John Kessenich4016e382016-07-15 11:53:56 -0600918 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600919 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600920
John Kessenich140f3df2015-06-26 16:58:36 -0600921 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
922
923 switch (glslangIntermediate->getOutputPrimitive()) {
924 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
925 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
926 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600927 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600928 }
John Kessenich4016e382016-07-15 11:53:56 -0600929 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600930 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
931 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
932 break;
933
934 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600935 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600936 if (glslangIntermediate->getPixelCenterInteger())
937 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600938
John Kessenich140f3df2015-06-26 16:58:36 -0600939 if (glslangIntermediate->getOriginUpperLeft())
940 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600941 else
942 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600943
944 if (glslangIntermediate->getEarlyFragmentTests())
945 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
946
947 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600948 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
949 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954
955 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
956 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 break;
958
959 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600960 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600961 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
962 glslangIntermediate->getLocalSize(1),
963 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600964 break;
965
966 default:
967 break;
968 }
John Kessenich140f3df2015-06-26 16:58:36 -0600969}
970
John Kessenichfca82622016-11-26 13:23:20 -0700971// Finish creating SPV, after the traversal is complete.
972void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700973{
John Kessenich517fe7a2016-11-26 13:31:47 -0700974 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700975 builder.setBuildPoint(shaderEntry->getLastBlock());
976 builder.leaveFunction();
977 }
978
John Kessenich7ba63412015-12-20 17:37:07 -0700979 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100980 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
981 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700982
qiningda397332016-03-09 19:54:03 -0500983 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700984}
985
John Kessenichfca82622016-11-26 13:23:20 -0700986// Write the SPV into 'out'.
987void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600988{
John Kessenichfca82622016-11-26 13:23:20 -0700989 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600990}
991
992//
993// Implement the traversal functions.
994//
995// Return true from interior nodes to have the external traversal
996// continue on to children. Return false if children were
997// already processed.
998//
999
1000//
qining25262b32016-05-06 17:25:16 -04001001// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001002// - uniform/input reads
1003// - output writes
1004// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1005// - something simple that degenerates into the last bullet
1006//
1007void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1008{
qining75d1d802016-04-06 14:42:01 -04001009 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1010 if (symbol->getType().getQualifier().isSpecConstant())
1011 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1012
John Kessenich140f3df2015-06-26 16:58:36 -06001013 // getSymbolId() will set up all the IO decorations on the first call.
1014 // Formal function parameters were mapped during makeFunctions().
1015 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001016
1017 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1018 if (builder.isPointer(id)) {
1019 spv::StorageClass sc = builder.getStorageClass(id);
1020 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1021 iOSet.insert(id);
1022 }
1023
1024 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001025 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001026 // Prepare to generate code for the access
1027
1028 // L-value chains will be computed left to right. We're on the symbol now,
1029 // which is the left-most part of the access chain, so now is "clear" time,
1030 // followed by setting the base.
1031 builder.clearAccessChain();
1032
1033 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001034 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001035 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001036 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001037 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001038 // These are also pure R-values.
1039 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001040 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001041 builder.setAccessChainRValue(id);
1042 else
1043 builder.setAccessChainLValue(id);
1044 }
1045}
1046
1047bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1048{
qining40887662016-04-03 22:20:42 -04001049 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1050 if (node->getType().getQualifier().isSpecConstant())
1051 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1052
John Kessenich140f3df2015-06-26 16:58:36 -06001053 // First, handle special cases
1054 switch (node->getOp()) {
1055 case glslang::EOpAssign:
1056 case glslang::EOpAddAssign:
1057 case glslang::EOpSubAssign:
1058 case glslang::EOpMulAssign:
1059 case glslang::EOpVectorTimesMatrixAssign:
1060 case glslang::EOpVectorTimesScalarAssign:
1061 case glslang::EOpMatrixTimesScalarAssign:
1062 case glslang::EOpMatrixTimesMatrixAssign:
1063 case glslang::EOpDivAssign:
1064 case glslang::EOpModAssign:
1065 case glslang::EOpAndAssign:
1066 case glslang::EOpInclusiveOrAssign:
1067 case glslang::EOpExclusiveOrAssign:
1068 case glslang::EOpLeftShiftAssign:
1069 case glslang::EOpRightShiftAssign:
1070 // A bin-op assign "a += b" means the same thing as "a = a + b"
1071 // where a is evaluated before b. For a simple assignment, GLSL
1072 // says to evaluate the left before the right. So, always, left
1073 // node then right node.
1074 {
1075 // get the left l-value, save it away
1076 builder.clearAccessChain();
1077 node->getLeft()->traverse(this);
1078 spv::Builder::AccessChain lValue = builder.getAccessChain();
1079
1080 // evaluate the right
1081 builder.clearAccessChain();
1082 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001083 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001084
1085 if (node->getOp() != glslang::EOpAssign) {
1086 // the left is also an r-value
1087 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001088 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001089
1090 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001091 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001092 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001093 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1094 node->getType().getBasicType());
1095
1096 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001097 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001098 }
1099
1100 // store the result
1101 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001102 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001103
1104 // assignments are expressions having an rValue after they are evaluated...
1105 builder.clearAccessChain();
1106 builder.setAccessChainRValue(rValue);
1107 }
1108 return false;
1109 case glslang::EOpIndexDirect:
1110 case glslang::EOpIndexDirectStruct:
1111 {
1112 // Get the left part of the access chain.
1113 node->getLeft()->traverse(this);
1114
1115 // Add the next element in the chain
1116
David Netoa901ffe2016-06-08 14:11:40 +01001117 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001118 if (! node->getLeft()->getType().isArray() &&
1119 node->getLeft()->getType().isVector() &&
1120 node->getOp() == glslang::EOpIndexDirect) {
1121 // This is essentially a hard-coded vector swizzle of size 1,
1122 // so short circuit the access-chain stuff with a swizzle.
1123 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001124 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001125 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001126 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001127 int spvIndex = glslangIndex;
1128 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1129 node->getOp() == glslang::EOpIndexDirectStruct)
1130 {
1131 // This may be, e.g., an anonymous block-member selection, which generally need
1132 // index remapping due to hidden members in anonymous blocks.
1133 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1134 assert(remapper.size() > 0);
1135 spvIndex = remapper[glslangIndex];
1136 }
John Kessenichebb50532016-05-16 19:22:05 -06001137
David Netoa901ffe2016-06-08 14:11:40 +01001138 // normal case for indexing array or structure or block
1139 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1140
1141 // Add capabilities here for accessing PointSize and clip/cull distance.
1142 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001143 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001144 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001145 }
1146 }
1147 return false;
1148 case glslang::EOpIndexIndirect:
1149 {
1150 // Structure or array or vector indirection.
1151 // Will use native SPIR-V access-chain for struct and array indirection;
1152 // matrices are arrays of vectors, so will also work for a matrix.
1153 // Will use the access chain's 'component' for variable index into a vector.
1154
1155 // This adapter is building access chains left to right.
1156 // Set up the access chain to the left.
1157 node->getLeft()->traverse(this);
1158
1159 // save it so that computing the right side doesn't trash it
1160 spv::Builder::AccessChain partial = builder.getAccessChain();
1161
1162 // compute the next index in the chain
1163 builder.clearAccessChain();
1164 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001165 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001166
1167 // restore the saved access chain
1168 builder.setAccessChain(partial);
1169
1170 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001171 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001172 else
John Kessenichfa668da2015-09-13 14:46:30 -06001173 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001174 }
1175 return false;
1176 case glslang::EOpVectorSwizzle:
1177 {
1178 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001179 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001180 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001181 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001182 }
1183 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001184 case glslang::EOpMatrixSwizzle:
1185 logger->missingFunctionality("matrix swizzle");
1186 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001187 case glslang::EOpLogicalOr:
1188 case glslang::EOpLogicalAnd:
1189 {
1190
1191 // These may require short circuiting, but can sometimes be done as straight
1192 // binary operations. The right operand must be short circuited if it has
1193 // side effects, and should probably be if it is complex.
1194 if (isTrivial(node->getRight()->getAsTyped()))
1195 break; // handle below as a normal binary operation
1196 // otherwise, we need to do dynamic short circuiting on the right operand
1197 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1198 builder.clearAccessChain();
1199 builder.setAccessChainRValue(result);
1200 }
1201 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001202 default:
1203 break;
1204 }
1205
1206 // Assume generic binary op...
1207
John Kessenich32cfd492016-02-02 12:37:46 -07001208 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001209 builder.clearAccessChain();
1210 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001211 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001212
John Kessenich32cfd492016-02-02 12:37:46 -07001213 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001214 builder.clearAccessChain();
1215 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001216 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001217
John Kessenich32cfd492016-02-02 12:37:46 -07001218 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001219 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001220 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001221 convertGlslangToSpvType(node->getType()), left, right,
1222 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
John Kessenich50e57562015-12-21 21:21:11 -07001224 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001225 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001226 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001227 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001228 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001229 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001230 return false;
1231 }
John Kessenich140f3df2015-06-26 16:58:36 -06001232}
1233
1234bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1235{
qining40887662016-04-03 22:20:42 -04001236 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1237 if (node->getType().getQualifier().isSpecConstant())
1238 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1239
John Kessenichfc51d282015-08-19 13:34:18 -06001240 spv::Id result = spv::NoResult;
1241
1242 // try texturing first
1243 result = createImageTextureFunctionCall(node);
1244 if (result != spv::NoResult) {
1245 builder.clearAccessChain();
1246 builder.setAccessChainRValue(result);
1247
1248 return false; // done with this node
1249 }
1250
1251 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001252
1253 if (node->getOp() == glslang::EOpArrayLength) {
1254 // Quite special; won't want to evaluate the operand.
1255
1256 // Normal .length() would have been constant folded by the front-end.
1257 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001258 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001259 assert(node->getOperand()->getType().isRuntimeSizedArray());
1260 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1261 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001262 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1263 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001264
1265 builder.clearAccessChain();
1266 builder.setAccessChainRValue(length);
1267
1268 return false;
1269 }
1270
John Kessenichfc51d282015-08-19 13:34:18 -06001271 // Start by evaluating the operand
1272
John Kessenich8c8505c2016-07-26 12:50:38 -06001273 // Does it need a swizzle inversion? If so, evaluation is inverted;
1274 // operate first on the swizzle base, then apply the swizzle.
1275 spv::Id invertedType = spv::NoType;
1276 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1277 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1278 invertedType = getInvertedSwizzleType(*node->getOperand());
1279
John Kessenich140f3df2015-06-26 16:58:36 -06001280 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001281 if (invertedType != spv::NoType)
1282 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1283 else
1284 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001285
Rex Xufc618912015-09-09 16:42:49 +08001286 spv::Id operand = spv::NoResult;
1287
1288 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1289 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001290 node->getOp() == glslang::EOpAtomicCounter ||
1291 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001292 operand = builder.accessChainGetLValue(); // Special case l-value operands
1293 else
John Kessenich32cfd492016-02-02 12:37:46 -07001294 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001295
John Kessenichf6640762016-08-01 19:44:00 -06001296 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001297 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001300 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001301 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 // if not, then possibly an operation
1304 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001305 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001306
1307 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001308 if (invertedType)
1309 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1310
John Kessenich140f3df2015-06-26 16:58:36 -06001311 builder.clearAccessChain();
1312 builder.setAccessChainRValue(result);
1313
1314 return false; // done with this node
1315 }
1316
1317 // it must be a special case, check...
1318 switch (node->getOp()) {
1319 case glslang::EOpPostIncrement:
1320 case glslang::EOpPostDecrement:
1321 case glslang::EOpPreIncrement:
1322 case glslang::EOpPreDecrement:
1323 {
1324 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001325 spv::Id one = 0;
1326 if (node->getBasicType() == glslang::EbtFloat)
1327 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001328 else if (node->getBasicType() == glslang::EbtDouble)
1329 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001330#ifdef AMD_EXTENSIONS
1331 else if (node->getBasicType() == glslang::EbtFloat16)
1332 one = builder.makeFloat16Constant(1.0F);
1333#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001334 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1335 one = builder.makeInt64Constant(1);
1336 else
1337 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001338 glslang::TOperator op;
1339 if (node->getOp() == glslang::EOpPreIncrement ||
1340 node->getOp() == glslang::EOpPostIncrement)
1341 op = glslang::EOpAdd;
1342 else
1343 op = glslang::EOpSub;
1344
John Kessenichf6640762016-08-01 19:44:00 -06001345 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001346 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001347 convertGlslangToSpvType(node->getType()), operand, one,
1348 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001349 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001350
1351 // The result of operation is always stored, but conditionally the
1352 // consumed result. The consumed result is always an r-value.
1353 builder.accessChainStore(result);
1354 builder.clearAccessChain();
1355 if (node->getOp() == glslang::EOpPreIncrement ||
1356 node->getOp() == glslang::EOpPreDecrement)
1357 builder.setAccessChainRValue(result);
1358 else
1359 builder.setAccessChainRValue(operand);
1360 }
1361
1362 return false;
1363
1364 case glslang::EOpEmitStreamVertex:
1365 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1366 return false;
1367 case glslang::EOpEndStreamPrimitive:
1368 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1369 return false;
1370
1371 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001372 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001373 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001374 }
John Kessenich140f3df2015-06-26 16:58:36 -06001375}
1376
1377bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1378{
qining27e04a02016-04-14 16:40:20 -04001379 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1380 if (node->getType().getQualifier().isSpecConstant())
1381 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1382
John Kessenichfc51d282015-08-19 13:34:18 -06001383 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001384 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1385 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001386
1387 // try texturing
1388 result = createImageTextureFunctionCall(node);
1389 if (result != spv::NoResult) {
1390 builder.clearAccessChain();
1391 builder.setAccessChainRValue(result);
1392
1393 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001394 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001395 // "imageStore" is a special case, which has no result
1396 return false;
1397 }
John Kessenichfc51d282015-08-19 13:34:18 -06001398
John Kessenich140f3df2015-06-26 16:58:36 -06001399 glslang::TOperator binOp = glslang::EOpNull;
1400 bool reduceComparison = true;
1401 bool isMatrix = false;
1402 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001403 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001404
1405 assert(node->getOp());
1406
John Kessenichf6640762016-08-01 19:44:00 -06001407 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001408
1409 switch (node->getOp()) {
1410 case glslang::EOpSequence:
1411 {
1412 if (preVisit)
1413 ++sequenceDepth;
1414 else
1415 --sequenceDepth;
1416
1417 if (sequenceDepth == 1) {
1418 // If this is the parent node of all the functions, we want to see them
1419 // early, so all call points have actual SPIR-V functions to reference.
1420 // In all cases, still let the traverser visit the children for us.
1421 makeFunctions(node->getAsAggregate()->getSequence());
1422
John Kessenich6fccb3c2016-09-19 16:01:41 -06001423 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001424 // anything else gets there, so visit out of order, doing them all now.
1425 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1426
John Kessenich6a60c2f2016-12-08 21:01:59 -07001427 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001428 // so do them manually.
1429 visitFunctions(node->getAsAggregate()->getSequence());
1430
1431 return false;
1432 }
1433
1434 return true;
1435 }
1436 case glslang::EOpLinkerObjects:
1437 {
1438 if (visit == glslang::EvPreVisit)
1439 linkageOnly = true;
1440 else
1441 linkageOnly = false;
1442
1443 return true;
1444 }
1445 case glslang::EOpComma:
1446 {
1447 // processing from left to right naturally leaves the right-most
1448 // lying around in the access chain
1449 glslang::TIntermSequence& glslangOperands = node->getSequence();
1450 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1451 glslangOperands[i]->traverse(this);
1452
1453 return false;
1454 }
1455 case glslang::EOpFunction:
1456 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001457 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001458 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001459 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001460 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001461 } else {
1462 handleFunctionEntry(node);
1463 }
1464 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001465 if (inEntryPoint)
1466 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001467 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001468 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001469 }
1470
1471 return true;
1472 case glslang::EOpParameters:
1473 // Parameters will have been consumed by EOpFunction processing, but not
1474 // the body, so we still visited the function node's children, making this
1475 // child redundant.
1476 return false;
1477 case glslang::EOpFunctionCall:
1478 {
1479 if (node->isUserDefined())
1480 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001481 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001482 if (result) {
1483 builder.clearAccessChain();
1484 builder.setAccessChainRValue(result);
1485 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001486 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001487
1488 return false;
1489 }
1490 case glslang::EOpConstructMat2x2:
1491 case glslang::EOpConstructMat2x3:
1492 case glslang::EOpConstructMat2x4:
1493 case glslang::EOpConstructMat3x2:
1494 case glslang::EOpConstructMat3x3:
1495 case glslang::EOpConstructMat3x4:
1496 case glslang::EOpConstructMat4x2:
1497 case glslang::EOpConstructMat4x3:
1498 case glslang::EOpConstructMat4x4:
1499 case glslang::EOpConstructDMat2x2:
1500 case glslang::EOpConstructDMat2x3:
1501 case glslang::EOpConstructDMat2x4:
1502 case glslang::EOpConstructDMat3x2:
1503 case glslang::EOpConstructDMat3x3:
1504 case glslang::EOpConstructDMat3x4:
1505 case glslang::EOpConstructDMat4x2:
1506 case glslang::EOpConstructDMat4x3:
1507 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001508#ifdef AMD_EXTENSIONS
1509 case glslang::EOpConstructF16Mat2x2:
1510 case glslang::EOpConstructF16Mat2x3:
1511 case glslang::EOpConstructF16Mat2x4:
1512 case glslang::EOpConstructF16Mat3x2:
1513 case glslang::EOpConstructF16Mat3x3:
1514 case glslang::EOpConstructF16Mat3x4:
1515 case glslang::EOpConstructF16Mat4x2:
1516 case glslang::EOpConstructF16Mat4x3:
1517 case glslang::EOpConstructF16Mat4x4:
1518#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001519 isMatrix = true;
1520 // fall through
1521 case glslang::EOpConstructFloat:
1522 case glslang::EOpConstructVec2:
1523 case glslang::EOpConstructVec3:
1524 case glslang::EOpConstructVec4:
1525 case glslang::EOpConstructDouble:
1526 case glslang::EOpConstructDVec2:
1527 case glslang::EOpConstructDVec3:
1528 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001529#ifdef AMD_EXTENSIONS
1530 case glslang::EOpConstructFloat16:
1531 case glslang::EOpConstructF16Vec2:
1532 case glslang::EOpConstructF16Vec3:
1533 case glslang::EOpConstructF16Vec4:
1534#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001535 case glslang::EOpConstructBool:
1536 case glslang::EOpConstructBVec2:
1537 case glslang::EOpConstructBVec3:
1538 case glslang::EOpConstructBVec4:
1539 case glslang::EOpConstructInt:
1540 case glslang::EOpConstructIVec2:
1541 case glslang::EOpConstructIVec3:
1542 case glslang::EOpConstructIVec4:
1543 case glslang::EOpConstructUint:
1544 case glslang::EOpConstructUVec2:
1545 case glslang::EOpConstructUVec3:
1546 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001547 case glslang::EOpConstructInt64:
1548 case glslang::EOpConstructI64Vec2:
1549 case glslang::EOpConstructI64Vec3:
1550 case glslang::EOpConstructI64Vec4:
1551 case glslang::EOpConstructUint64:
1552 case glslang::EOpConstructU64Vec2:
1553 case glslang::EOpConstructU64Vec3:
1554 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001555 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001556 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001557 {
1558 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001559 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001560 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001561 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001562 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001563 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001564 std::vector<spv::Id> constituents;
1565 for (int c = 0; c < (int)arguments.size(); ++c)
1566 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001567 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001568 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001569 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001570 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001571 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001572
1573 builder.clearAccessChain();
1574 builder.setAccessChainRValue(constructed);
1575
1576 return false;
1577 }
1578
1579 // These six are component-wise compares with component-wise results.
1580 // Forward on to createBinaryOperation(), requesting a vector result.
1581 case glslang::EOpLessThan:
1582 case glslang::EOpGreaterThan:
1583 case glslang::EOpLessThanEqual:
1584 case glslang::EOpGreaterThanEqual:
1585 case glslang::EOpVectorEqual:
1586 case glslang::EOpVectorNotEqual:
1587 {
1588 // Map the operation to a binary
1589 binOp = node->getOp();
1590 reduceComparison = false;
1591 switch (node->getOp()) {
1592 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1593 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1594 default: binOp = node->getOp(); break;
1595 }
1596
1597 break;
1598 }
1599 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001600 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001601 binOp = glslang::EOpMul;
1602 break;
1603 case glslang::EOpOuterProduct:
1604 // two vectors multiplied to make a matrix
1605 binOp = glslang::EOpOuterProduct;
1606 break;
1607 case glslang::EOpDot:
1608 {
qining25262b32016-05-06 17:25:16 -04001609 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001610 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001611 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001612 binOp = glslang::EOpMul;
1613 break;
1614 }
1615 case glslang::EOpMod:
1616 // when an aggregate, this is the floating-point mod built-in function,
1617 // which can be emitted by the one in createBinaryOperation()
1618 binOp = glslang::EOpMod;
1619 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001620 case glslang::EOpEmitVertex:
1621 case glslang::EOpEndPrimitive:
1622 case glslang::EOpBarrier:
1623 case glslang::EOpMemoryBarrier:
1624 case glslang::EOpMemoryBarrierAtomicCounter:
1625 case glslang::EOpMemoryBarrierBuffer:
1626 case glslang::EOpMemoryBarrierImage:
1627 case glslang::EOpMemoryBarrierShared:
1628 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001629 case glslang::EOpAllMemoryBarrierWithGroupSync:
1630 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1631 case glslang::EOpWorkgroupMemoryBarrier:
1632 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001633 noReturnValue = true;
1634 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1635 break;
1636
John Kessenich426394d2015-07-23 10:22:48 -06001637 case glslang::EOpAtomicAdd:
1638 case glslang::EOpAtomicMin:
1639 case glslang::EOpAtomicMax:
1640 case glslang::EOpAtomicAnd:
1641 case glslang::EOpAtomicOr:
1642 case glslang::EOpAtomicXor:
1643 case glslang::EOpAtomicExchange:
1644 case glslang::EOpAtomicCompSwap:
1645 atomic = true;
1646 break;
1647
John Kessenich140f3df2015-06-26 16:58:36 -06001648 default:
1649 break;
1650 }
1651
1652 //
1653 // See if it maps to a regular operation.
1654 //
John Kessenich140f3df2015-06-26 16:58:36 -06001655 if (binOp != glslang::EOpNull) {
1656 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1657 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1658 assert(left && right);
1659
1660 builder.clearAccessChain();
1661 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001662 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001663
1664 builder.clearAccessChain();
1665 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001666 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001667
qining25262b32016-05-06 17:25:16 -04001668 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001669 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001670 left->getType().getBasicType(), reduceComparison);
1671
1672 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001673 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001674 builder.clearAccessChain();
1675 builder.setAccessChainRValue(result);
1676
1677 return false;
1678 }
1679
John Kessenich426394d2015-07-23 10:22:48 -06001680 //
1681 // Create the list of operands.
1682 //
John Kessenich140f3df2015-06-26 16:58:36 -06001683 glslang::TIntermSequence& glslangOperands = node->getSequence();
1684 std::vector<spv::Id> operands;
1685 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001686 // special case l-value operands; there are just a few
1687 bool lvalue = false;
1688 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001689 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001690 case glslang::EOpModf:
1691 if (arg == 1)
1692 lvalue = true;
1693 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001694 case glslang::EOpInterpolateAtSample:
1695 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001696#ifdef AMD_EXTENSIONS
1697 case glslang::EOpInterpolateAtVertex:
1698#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001699 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001700 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001701
1702 // Does it need a swizzle inversion? If so, evaluation is inverted;
1703 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001704 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1706 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1707 }
Rex Xu7a26c172015-12-08 17:12:09 +08001708 break;
Rex Xud4782c12015-09-06 16:30:11 +08001709 case glslang::EOpAtomicAdd:
1710 case glslang::EOpAtomicMin:
1711 case glslang::EOpAtomicMax:
1712 case glslang::EOpAtomicAnd:
1713 case glslang::EOpAtomicOr:
1714 case glslang::EOpAtomicXor:
1715 case glslang::EOpAtomicExchange:
1716 case glslang::EOpAtomicCompSwap:
1717 if (arg == 0)
1718 lvalue = true;
1719 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001720 case glslang::EOpAddCarry:
1721 case glslang::EOpSubBorrow:
1722 if (arg == 2)
1723 lvalue = true;
1724 break;
1725 case glslang::EOpUMulExtended:
1726 case glslang::EOpIMulExtended:
1727 if (arg >= 2)
1728 lvalue = true;
1729 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001730 default:
1731 break;
1732 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001733 builder.clearAccessChain();
1734 if (invertedType != spv::NoType && arg == 0)
1735 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1736 else
1737 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001738 if (lvalue)
1739 operands.push_back(builder.accessChainGetLValue());
1740 else
John Kessenich32cfd492016-02-02 12:37:46 -07001741 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001742 }
John Kessenich426394d2015-07-23 10:22:48 -06001743
1744 if (atomic) {
1745 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001746 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001747 } else {
1748 // Pass through to generic operations.
1749 switch (glslangOperands.size()) {
1750 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001751 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001752 break;
1753 case 1:
qining25262b32016-05-06 17:25:16 -04001754 result = createUnaryOperation(
1755 node->getOp(), precision,
1756 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001758 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001759 break;
1760 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001761 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001762 break;
1763 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001764 if (invertedType)
1765 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001766 }
1767
1768 if (noReturnValue)
1769 return false;
1770
1771 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001772 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001773 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001774 } else {
1775 builder.clearAccessChain();
1776 builder.setAccessChainRValue(result);
1777 return false;
1778 }
1779}
1780
John Kessenich433e9ff2017-01-26 20:31:11 -07001781// This path handles both if-then-else and ?:
1782// The if-then-else has a node type of void, while
1783// ?: has either a void or a non-void node type
1784//
1785// Leaving the result, when not void:
1786// GLSL only has r-values as the result of a :?, but
1787// if we have an l-value, that can be more efficient if it will
1788// become the base of a complex r-value expression, because the
1789// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001790bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1791{
John Kessenich433e9ff2017-01-26 20:31:11 -07001792 // See if it simple and safe to generate OpSelect instead of using control flow.
1793 // Crucially, side effects must be avoided, and there are performance trade-offs.
1794 // Return true if good idea (and safe) for OpSelect, false otherwise.
1795 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001796 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1797 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001798 return false;
1799
1800 if (node->getTrueBlock() == nullptr ||
1801 node->getFalseBlock() == nullptr)
1802 return false;
1803
1804 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1805 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1806
1807 // return true if a single operand to ? : is okay for OpSelect
1808 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001809 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001810 };
1811
1812 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1813 operandOkay(node->getFalseBlock()->getAsTyped());
1814 };
1815
1816 // Emit OpSelect for this selection.
1817 const auto handleAsOpSelect = [&]() {
1818 node->getCondition()->traverse(this);
1819 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1820 node->getTrueBlock()->traverse(this);
1821 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1822 node->getFalseBlock()->traverse(this);
1823 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1824
1825 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1826 builder.clearAccessChain();
1827 builder.setAccessChainRValue(select);
1828 };
1829
1830 // Try for OpSelect
1831
1832 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001833 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1834 if (node->getType().getQualifier().isSpecConstant())
1835 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1836
John Kessenich433e9ff2017-01-26 20:31:11 -07001837 handleAsOpSelect();
1838 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001839 }
1840
John Kessenich433e9ff2017-01-26 20:31:11 -07001841 // Instead, emit control flow...
1842
1843 // Don't handle results as temporaries, because there will be two names
1844 // and better to leave SSA to later passes.
1845 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1846 ? spv::NoResult
1847 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1848
John Kessenich140f3df2015-06-26 16:58:36 -06001849 // emit the condition before doing anything with selection
1850 node->getCondition()->traverse(this);
1851
1852 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001853 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001854
John Kessenich433e9ff2017-01-26 20:31:11 -07001855 // emit the "then" statement
1856 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001857 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001858 if (result != spv::NoResult)
1859 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861
John Kessenich433e9ff2017-01-26 20:31:11 -07001862 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001863 ifBuilder.makeBeginElse();
1864 // emit the "else" statement
1865 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001866 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001867 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001868 }
1869
John Kessenich433e9ff2017-01-26 20:31:11 -07001870 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001871 ifBuilder.makeEndIf();
1872
John Kessenich433e9ff2017-01-26 20:31:11 -07001873 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001874 // GLSL only has r-values as the result of a :?, but
1875 // if we have an l-value, that can be more efficient if it will
1876 // become the base of a complex r-value expression, because the
1877 // next layer copies r-values into memory to use the access-chain mechanism
1878 builder.clearAccessChain();
1879 builder.setAccessChainLValue(result);
1880 }
1881
1882 return false;
1883}
1884
1885bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1886{
1887 // emit and get the condition before doing anything with switch
1888 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001889 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
1891 // browse the children to sort out code segments
1892 int defaultSegment = -1;
1893 std::vector<TIntermNode*> codeSegments;
1894 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1895 std::vector<int> caseValues;
1896 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1897 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1898 TIntermNode* child = *c;
1899 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001900 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001901 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001902 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001903 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1904 } else
1905 codeSegments.push_back(child);
1906 }
1907
qining25262b32016-05-06 17:25:16 -04001908 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001909 // statements between the last case and the end of the switch statement
1910 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1911 (int)codeSegments.size() == defaultSegment)
1912 codeSegments.push_back(nullptr);
1913
1914 // make the switch statement
1915 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001916 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001917
1918 // emit all the code in the segments
1919 breakForLoop.push(false);
1920 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1921 builder.nextSwitchSegment(segmentBlocks, s);
1922 if (codeSegments[s])
1923 codeSegments[s]->traverse(this);
1924 else
1925 builder.addSwitchBreak();
1926 }
1927 breakForLoop.pop();
1928
1929 builder.endSwitch(segmentBlocks);
1930
1931 return false;
1932}
1933
1934void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1935{
1936 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001937 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001938
1939 builder.clearAccessChain();
1940 builder.setAccessChainRValue(constant);
1941}
1942
1943bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1944{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001945 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001946 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001947 // Spec requires back edges to target header blocks, and every header block
1948 // must dominate its merge block. Make a header block first to ensure these
1949 // conditions are met. By definition, it will contain OpLoopMerge, followed
1950 // by a block-ending branch. But we don't want to put any other body/test
1951 // instructions in it, since the body/test may have arbitrary instructions,
1952 // including merges of its own.
1953 builder.setBuildPoint(&blocks.head);
1954 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001955 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001956 spv::Block& test = builder.makeNewBlock();
1957 builder.createBranch(&test);
1958
1959 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001960 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001961 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001962 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001963 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1964
1965 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001966 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001967 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001968 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001969 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001970 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001971
1972 builder.setBuildPoint(&blocks.continue_target);
1973 if (node->getTerminal())
1974 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001975 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001976 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001977 builder.createBranch(&blocks.body);
1978
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001979 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001980 builder.setBuildPoint(&blocks.body);
1981 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001982 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001983 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001984 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001985
1986 builder.setBuildPoint(&blocks.continue_target);
1987 if (node->getTerminal())
1988 node->getTerminal()->traverse(this);
1989 if (node->getTest()) {
1990 node->getTest()->traverse(this);
1991 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001992 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001993 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001994 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001995 // TODO: unless there was a break/return/discard instruction
1996 // somewhere in the body, this is an infinite loop, so we should
1997 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001998 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001999 }
John Kessenich140f3df2015-06-26 16:58:36 -06002000 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002001 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002002 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002003 return false;
2004}
2005
2006bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2007{
2008 if (node->getExpression())
2009 node->getExpression()->traverse(this);
2010
2011 switch (node->getFlowOp()) {
2012 case glslang::EOpKill:
2013 builder.makeDiscard();
2014 break;
2015 case glslang::EOpBreak:
2016 if (breakForLoop.top())
2017 builder.createLoopExit();
2018 else
2019 builder.addSwitchBreak();
2020 break;
2021 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002022 builder.createLoopContinue();
2023 break;
2024 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002025 if (node->getExpression()) {
2026 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2027 spv::Id returnId = accessChainLoad(glslangReturnType);
2028 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2029 builder.clearAccessChain();
2030 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2031 builder.setAccessChainLValue(copyId);
2032 multiTypeStore(glslangReturnType, returnId);
2033 returnId = builder.createLoad(copyId);
2034 }
2035 builder.makeReturn(false, returnId);
2036 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002037 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002038
2039 builder.clearAccessChain();
2040 break;
2041
2042 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002043 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 break;
2045 }
2046
2047 return false;
2048}
2049
2050spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2051{
qining25262b32016-05-06 17:25:16 -04002052 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002053 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002054 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002055 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002056 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002057 }
2058
2059 // Now, handle actual variables
2060 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2061 spv::Id spvType = convertGlslangToSpvType(node->getType());
2062
2063 const char* name = node->getName().c_str();
2064 if (glslang::IsAnonymous(name))
2065 name = "";
2066
2067 return builder.createVariable(storageClass, spvType, name);
2068}
2069
2070// Return type Id of the sampled type.
2071spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2072{
2073 switch (sampler.type) {
2074 case glslang::EbtFloat: return builder.makeFloatType(32);
2075 case glslang::EbtInt: return builder.makeIntType(32);
2076 case glslang::EbtUint: return builder.makeUintType(32);
2077 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002078 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 return builder.makeFloatType(32);
2080 }
2081}
2082
John Kessenich8c8505c2016-07-26 12:50:38 -06002083// If node is a swizzle operation, return the type that should be used if
2084// the swizzle base is first consumed by another operation, before the swizzle
2085// is applied.
2086spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2087{
John Kessenichecba76f2017-01-06 00:34:48 -07002088 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002089 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2090 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2091 else
2092 return spv::NoType;
2093}
2094
2095// When inverting a swizzle with a parent op, this function
2096// will apply the swizzle operation to a completed parent operation.
2097spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2098{
2099 std::vector<unsigned> swizzle;
2100 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2101 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2102}
2103
John Kessenich8c8505c2016-07-26 12:50:38 -06002104// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2105void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2106{
2107 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2108 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2109 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2110}
2111
John Kessenich3ac051e2015-12-20 11:29:16 -07002112// Convert from a glslang type to an SPV type, by calling into a
2113// recursive version of this function. This establishes the inherited
2114// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002115spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2116{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002117 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002118}
2119
2120// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002121// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002122// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002123spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002124{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002125 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002126
2127 switch (type.getBasicType()) {
2128 case glslang::EbtVoid:
2129 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002130 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002131 break;
2132 case glslang::EbtFloat:
2133 spvType = builder.makeFloatType(32);
2134 break;
2135 case glslang::EbtDouble:
2136 spvType = builder.makeFloatType(64);
2137 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002138#ifdef AMD_EXTENSIONS
2139 case glslang::EbtFloat16:
2140 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002141 spvType = builder.makeFloatType(16);
2142 break;
2143#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002144 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002145 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2146 // a 32-bit int where non-0 means true.
2147 if (explicitLayout != glslang::ElpNone)
2148 spvType = builder.makeUintType(32);
2149 else
2150 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002151 break;
2152 case glslang::EbtInt:
2153 spvType = builder.makeIntType(32);
2154 break;
2155 case glslang::EbtUint:
2156 spvType = builder.makeUintType(32);
2157 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002158 case glslang::EbtInt64:
2159 builder.addCapability(spv::CapabilityInt64);
2160 spvType = builder.makeIntType(64);
2161 break;
2162 case glslang::EbtUint64:
2163 builder.addCapability(spv::CapabilityInt64);
2164 spvType = builder.makeUintType(64);
2165 break;
John Kessenich426394d2015-07-23 10:22:48 -06002166 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002167 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002168 spvType = builder.makeUintType(32);
2169 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002170 case glslang::EbtSampler:
2171 {
2172 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002173 if (sampler.sampler) {
2174 // pure sampler
2175 spvType = builder.makeSamplerType();
2176 } else {
2177 // an image is present, make its type
2178 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2179 sampler.image ? 2 : 1, TranslateImageFormat(type));
2180 if (sampler.combined) {
2181 // already has both image and sampler, make the combined type
2182 spvType = builder.makeSampledImageType(spvType);
2183 }
John Kessenich55e7d112015-11-15 21:33:39 -07002184 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002185 }
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EbtStruct:
2188 case glslang::EbtBlock:
2189 {
2190 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002191 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002192
2193 // Try to share structs for different layouts, but not yet for other
2194 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002195 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002196 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002197 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002198 break;
2199
2200 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002201 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002202 memberRemapper[glslangMembers].resize(glslangMembers->size());
2203 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002204 }
2205 break;
2206 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002207 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002208 break;
2209 }
2210
2211 if (type.isMatrix())
2212 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2213 else {
2214 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2215 if (type.getVectorSize() > 1)
2216 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2217 }
2218
2219 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002220 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2221
John Kessenichc9a80832015-09-12 12:17:44 -06002222 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002223 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002224 // We need to decorate array strides for types needing explicit layout, except blocks.
2225 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002226 // Use a dummy glslang type for querying internal strides of
2227 // arrays of arrays, but using just a one-dimensional array.
2228 glslang::TType simpleArrayType(type, 0); // deference type of the array
2229 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2230 simpleArrayType.getArraySizes().dereference();
2231
2232 // Will compute the higher-order strides here, rather than making a whole
2233 // pile of types and doing repetitive recursion on their contents.
2234 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2235 }
John Kessenichf8842e52016-01-04 19:22:56 -07002236
2237 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002238 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002239 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002240 if (stride > 0)
2241 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002242 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002243 }
2244 } else {
2245 // single-dimensional array, and don't yet have stride
2246
John Kessenichf8842e52016-01-04 19:22:56 -07002247 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002248 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2249 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002250 }
John Kessenich31ed4832015-09-09 17:51:38 -06002251
John Kessenichc9a80832015-09-12 12:17:44 -06002252 // Do the outer dimension, which might not be known for a runtime-sized array
2253 if (type.isRuntimeSizedArray()) {
2254 spvType = builder.makeRuntimeArray(spvType);
2255 } else {
2256 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002257 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002258 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002259 if (stride > 0)
2260 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002261 }
2262
2263 return spvType;
2264}
2265
John Kessenich6090df02016-06-30 21:18:02 -06002266// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2267// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2268// Mutually recursive with convertGlslangToSpvType().
2269spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2270 const glslang::TTypeList* glslangMembers,
2271 glslang::TLayoutPacking explicitLayout,
2272 const glslang::TQualifier& qualifier)
2273{
2274 // Create a vector of struct types for SPIR-V to consume
2275 std::vector<spv::Id> spvMembers;
2276 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2277 int locationOffset = 0; // for use across struct members, when they are called recursively
2278 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2279 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2280 if (glslangMember.hiddenMember()) {
2281 ++memberDelta;
2282 if (type.getBasicType() == glslang::EbtBlock)
2283 memberRemapper[glslangMembers][i] = -1;
2284 } else {
2285 if (type.getBasicType() == glslang::EbtBlock)
2286 memberRemapper[glslangMembers][i] = i - memberDelta;
2287 // modify just this child's view of the qualifier
2288 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2289 InheritQualifiers(memberQualifier, qualifier);
2290
2291 // manually inherit location; it's more complex
2292 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2293 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2294 if (qualifier.hasLocation())
2295 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2296
2297 // recurse
2298 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2299 }
2300 }
2301
2302 // Make the SPIR-V type
2303 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002304 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002305 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2306
2307 // Decorate it
2308 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2309
2310 return spvType;
2311}
2312
2313void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2314 const glslang::TTypeList* glslangMembers,
2315 glslang::TLayoutPacking explicitLayout,
2316 const glslang::TQualifier& qualifier,
2317 spv::Id spvType)
2318{
2319 // Name and decorate the non-hidden members
2320 int offset = -1;
2321 int locationOffset = 0; // for use within the members of this struct
2322 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2323 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2324 int member = i;
2325 if (type.getBasicType() == glslang::EbtBlock)
2326 member = memberRemapper[glslangMembers][i];
2327
2328 // modify just this child's view of the qualifier
2329 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2330 InheritQualifiers(memberQualifier, qualifier);
2331
2332 // using -1 above to indicate a hidden member
2333 if (member >= 0) {
2334 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2335 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2336 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2337 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002338 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2339 type.getQualifier().storage == glslang::EvqVaryingOut) {
2340 if (type.getBasicType() == glslang::EbtBlock ||
2341 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002342 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2343 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2344 }
2345 }
2346 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2347
2348 if (qualifier.storage == glslang::EvqBuffer) {
2349 std::vector<spv::Decoration> memory;
2350 TranslateMemoryDecoration(memberQualifier, memory);
2351 for (unsigned int i = 0; i < memory.size(); ++i)
2352 addMemberDecoration(spvType, member, memory[i]);
2353 }
2354
John Kessenich2f47bc92016-06-30 21:47:35 -06002355 // Compute location decoration; tricky based on whether inheritance is at play and
2356 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002357 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2358 // probably move to the linker stage of the front end proper, and just have the
2359 // answer sitting already distributed throughout the individual member locations.
2360 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002361 // Ignore member locations if the container is an array, as that's
2362 // ill-specified and decisions have been made to not allow this anyway.
2363 // The object itself must have a location, and that comes out from decorating the object,
2364 // not the type (this code decorates types).
2365 if (! type.isArray()) {
2366 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2367 // struct members should not have explicit locations
2368 assert(type.getBasicType() != glslang::EbtStruct);
2369 location = memberQualifier.layoutLocation;
2370 } else if (type.getBasicType() != glslang::EbtBlock) {
2371 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2372 // The members, and their nested types, must not themselves have Location decorations.
2373 } else if (qualifier.hasLocation()) // inheritance
2374 location = qualifier.layoutLocation + locationOffset;
2375 }
John Kessenich6090df02016-06-30 21:18:02 -06002376 if (location >= 0)
2377 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2378
John Kessenich2f47bc92016-06-30 21:47:35 -06002379 if (qualifier.hasLocation()) // track for upcoming inheritance
2380 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2381
John Kessenich6090df02016-06-30 21:18:02 -06002382 // component, XFB, others
2383 if (glslangMember.getQualifier().hasComponent())
2384 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2385 if (glslangMember.getQualifier().hasXfbOffset())
2386 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2387 else if (explicitLayout != glslang::ElpNone) {
2388 // figure out what to do with offset, which is accumulating
2389 int nextOffset;
2390 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2391 if (offset >= 0)
2392 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2393 offset = nextOffset;
2394 }
2395
2396 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2397 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2398
2399 // built-in variable decorations
2400 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002401 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002402 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002403
2404#ifdef NV_EXTENSIONS
2405 if (builtIn == spv::BuiltInLayer) {
2406 // SPV_NV_viewport_array2 extension
2407 if (glslangMember.getQualifier().layoutViewportRelative){
2408 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2409 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2410 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2411 }
2412 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2413 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2414 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2415 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2416 }
2417 }
chaocdf3956c2017-02-14 14:52:34 -08002418 if (glslangMember.getQualifier().layoutPassthrough) {
2419 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2420 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2421 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2422 }
chaoc771d89f2017-01-13 01:10:53 -08002423#endif
John Kessenich6090df02016-06-30 21:18:02 -06002424 }
2425 }
2426
2427 // Decorate the structure
2428 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2429 addDecoration(spvType, TranslateBlockDecoration(type));
2430 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2431 builder.addCapability(spv::CapabilityGeometryStreams);
2432 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2433 }
2434 if (glslangIntermediate->getXfbMode()) {
2435 builder.addCapability(spv::CapabilityTransformFeedback);
2436 if (type.getQualifier().hasXfbStride())
2437 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2438 if (type.getQualifier().hasXfbBuffer())
2439 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2440 }
2441}
2442
John Kessenich6c292d32016-02-15 20:58:50 -07002443// Turn the expression forming the array size into an id.
2444// This is not quite trivial, because of specialization constants.
2445// Sometimes, a raw constant is turned into an Id, and sometimes
2446// a specialization constant expression is.
2447spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2448{
2449 // First, see if this is sized with a node, meaning a specialization constant:
2450 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2451 if (specNode != nullptr) {
2452 builder.clearAccessChain();
2453 specNode->traverse(this);
2454 return accessChainLoad(specNode->getAsTyped()->getType());
2455 }
qining25262b32016-05-06 17:25:16 -04002456
John Kessenich6c292d32016-02-15 20:58:50 -07002457 // Otherwise, need a compile-time (front end) size, get it:
2458 int size = arraySizes.getDimSize(dim);
2459 assert(size > 0);
2460 return builder.makeUintConstant(size);
2461}
2462
John Kessenich103bef92016-02-08 21:38:15 -07002463// Wrap the builder's accessChainLoad to:
2464// - localize handling of RelaxedPrecision
2465// - use the SPIR-V inferred type instead of another conversion of the glslang type
2466// (avoids unnecessary work and possible type punning for structures)
2467// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002468spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2469{
John Kessenich103bef92016-02-08 21:38:15 -07002470 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2471 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2472
2473 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002474 if (type.getBasicType() == glslang::EbtBool) {
2475 if (builder.isScalarType(nominalTypeId)) {
2476 // Conversion for bool
2477 spv::Id boolType = builder.makeBoolType();
2478 if (nominalTypeId != boolType)
2479 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2480 } else if (builder.isVectorType(nominalTypeId)) {
2481 // Conversion for bvec
2482 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2483 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2484 if (nominalTypeId != bvecType)
2485 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2486 }
2487 }
John Kessenich103bef92016-02-08 21:38:15 -07002488
2489 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002490}
2491
Rex Xu27253232016-02-23 17:51:09 +08002492// Wrap the builder's accessChainStore to:
2493// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002494//
2495// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002496void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2497{
2498 // Need to convert to abstract types when necessary
2499 if (type.getBasicType() == glslang::EbtBool) {
2500 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2501
2502 if (builder.isScalarType(nominalTypeId)) {
2503 // Conversion for bool
2504 spv::Id boolType = builder.makeBoolType();
2505 if (nominalTypeId != boolType) {
2506 spv::Id zero = builder.makeUintConstant(0);
2507 spv::Id one = builder.makeUintConstant(1);
2508 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2509 }
2510 } else if (builder.isVectorType(nominalTypeId)) {
2511 // Conversion for bvec
2512 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2513 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2514 if (nominalTypeId != bvecType) {
2515 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2516 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2517 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2518 }
2519 }
2520 }
2521
2522 builder.accessChainStore(rvalue);
2523}
2524
John Kessenich4bf71552016-09-02 11:20:21 -06002525// For storing when types match at the glslang level, but not might match at the
2526// SPIR-V level.
2527//
2528// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002529// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002530// as in a member-decorated way.
2531//
2532// NOTE: This function can handle any store request; if it's not special it
2533// simplifies to a simple OpStore.
2534//
2535// Implicitly uses the existing builder.accessChain as the storage target.
2536void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2537{
John Kessenichb3e24e42016-09-11 12:33:43 -06002538 // we only do the complex path here if it's an aggregate
2539 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002540 accessChainStore(type, rValue);
2541 return;
2542 }
2543
John Kessenichb3e24e42016-09-11 12:33:43 -06002544 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002545 spv::Id rType = builder.getTypeId(rValue);
2546 spv::Id lValue = builder.accessChainGetLValue();
2547 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2548 if (lType == rType) {
2549 accessChainStore(type, rValue);
2550 return;
2551 }
2552
John Kessenichb3e24e42016-09-11 12:33:43 -06002553 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002554 // where the two types were the same type in GLSL. This requires member
2555 // by member copy, recursively.
2556
John Kessenichb3e24e42016-09-11 12:33:43 -06002557 // If an array, copy element by element.
2558 if (type.isArray()) {
2559 glslang::TType glslangElementType(type, 0);
2560 spv::Id elementRType = builder.getContainedTypeId(rType);
2561 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2562 // get the source member
2563 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002564
John Kessenichb3e24e42016-09-11 12:33:43 -06002565 // set up the target storage
2566 builder.clearAccessChain();
2567 builder.setAccessChainLValue(lValue);
2568 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002569
John Kessenichb3e24e42016-09-11 12:33:43 -06002570 // store the member
2571 multiTypeStore(glslangElementType, elementRValue);
2572 }
2573 } else {
2574 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002575
John Kessenichb3e24e42016-09-11 12:33:43 -06002576 // loop over structure members
2577 const glslang::TTypeList& members = *type.getStruct();
2578 for (int m = 0; m < (int)members.size(); ++m) {
2579 const glslang::TType& glslangMemberType = *members[m].type;
2580
2581 // get the source member
2582 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2583 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2584
2585 // set up the target storage
2586 builder.clearAccessChain();
2587 builder.setAccessChainLValue(lValue);
2588 builder.accessChainPush(builder.makeIntConstant(m));
2589
2590 // store the member
2591 multiTypeStore(glslangMemberType, memberRValue);
2592 }
John Kessenich4bf71552016-09-02 11:20:21 -06002593 }
2594}
2595
John Kessenichf85e8062015-12-19 13:57:10 -07002596// Decide whether or not this type should be
2597// decorated with offsets and strides, and if so
2598// whether std140 or std430 rules should be applied.
2599glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002600{
John Kessenichf85e8062015-12-19 13:57:10 -07002601 // has to be a block
2602 if (type.getBasicType() != glslang::EbtBlock)
2603 return glslang::ElpNone;
2604
2605 // has to be a uniform or buffer block
2606 if (type.getQualifier().storage != glslang::EvqUniform &&
2607 type.getQualifier().storage != glslang::EvqBuffer)
2608 return glslang::ElpNone;
2609
2610 // return the layout to use
2611 switch (type.getQualifier().layoutPacking) {
2612 case glslang::ElpStd140:
2613 case glslang::ElpStd430:
2614 return type.getQualifier().layoutPacking;
2615 default:
2616 return glslang::ElpNone;
2617 }
John Kessenich31ed4832015-09-09 17:51:38 -06002618}
2619
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002620// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002621int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002622{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002623 int size;
John Kessenich49987892015-12-29 17:11:44 -07002624 int stride;
2625 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002626
2627 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002628}
2629
John Kessenich49987892015-12-29 17:11:44 -07002630// 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 -07002631// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002632int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002633{
John Kessenich49987892015-12-29 17:11:44 -07002634 glslang::TType elementType;
2635 elementType.shallowCopy(matrixType);
2636 elementType.clearArraySizes();
2637
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002638 int size;
John Kessenich49987892015-12-29 17:11:44 -07002639 int stride;
2640 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2641
2642 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002643}
2644
John Kessenich5e4b1242015-08-06 22:53:06 -06002645// Given a member type of a struct, realign the current offset for it, and compute
2646// the next (not yet aligned) offset for the next member, which will get aligned
2647// on the next call.
2648// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2649// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2650// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002651void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002652 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002653{
2654 // this will get a positive value when deemed necessary
2655 nextOffset = -1;
2656
John Kessenich5e4b1242015-08-06 22:53:06 -06002657 // override anything in currentOffset with user-set offset
2658 if (memberType.getQualifier().hasOffset())
2659 currentOffset = memberType.getQualifier().layoutOffset;
2660
2661 // It could be that current linker usage in glslang updated all the layoutOffset,
2662 // in which case the following code does not matter. But, that's not quite right
2663 // once cross-compilation unit GLSL validation is done, as the original user
2664 // settings are needed in layoutOffset, and then the following will come into play.
2665
John Kessenichf85e8062015-12-19 13:57:10 -07002666 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002667 if (! memberType.getQualifier().hasOffset())
2668 currentOffset = -1;
2669
2670 return;
2671 }
2672
John Kessenichf85e8062015-12-19 13:57:10 -07002673 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002674 if (currentOffset < 0)
2675 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002676
John Kessenich5e4b1242015-08-06 22:53:06 -06002677 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2678 // but possibly not yet correctly aligned.
2679
2680 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002681 int dummyStride;
2682 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 glslang::RoundToPow2(currentOffset, memberAlignment);
2684 nextOffset = currentOffset + memberSize;
2685}
2686
David Netoa901ffe2016-06-08 14:11:40 +01002687void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002688{
David Netoa901ffe2016-06-08 14:11:40 +01002689 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2690 switch (glslangBuiltIn)
2691 {
2692 case glslang::EbvClipDistance:
2693 case glslang::EbvCullDistance:
2694 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002695#ifdef NV_EXTENSIONS
2696 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002697 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002698 case glslang::EbvViewportMaskNV:
2699 case glslang::EbvSecondaryPositionNV:
2700 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002701 case glslang::EbvPositionPerViewNV:
2702 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002703#endif
David Netoa901ffe2016-06-08 14:11:40 +01002704 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2705 // Alternately, we could just call this for any glslang built-in, since the
2706 // capability already guards against duplicates.
2707 TranslateBuiltInDecoration(glslangBuiltIn, false);
2708 break;
2709 default:
2710 // Capabilities were already generated when the struct was declared.
2711 break;
2712 }
John Kessenichebb50532016-05-16 19:22:05 -06002713}
2714
John Kessenich6fccb3c2016-09-19 16:01:41 -06002715bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002716{
John Kessenicheee9d532016-09-19 18:09:30 -06002717 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002718}
2719
2720// Make all the functions, skeletally, without actually visiting their bodies.
2721void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2722{
2723 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2724 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002725 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002726 continue;
2727
2728 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002729 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002730 //
qining25262b32016-05-06 17:25:16 -04002731 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002732 // function. What it is an address of varies:
2733 //
John Kessenich4bf71552016-09-02 11:20:21 -06002734 // - "in" parameters not marked as "const" can be written to without modifying the calling
2735 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002736 //
2737 // - "const in" parameters can just be the r-value, as no writes need occur.
2738 //
John Kessenich4bf71552016-09-02 11:20:21 -06002739 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2740 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06002741
2742 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002743 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002744 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2745
2746 for (int p = 0; p < (int)parameters.size(); ++p) {
2747 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2748 spv::Id typeId = convertGlslangToSpvType(paramType);
steve-lunargdd8287a2017-02-23 18:04:12 -07002749 if (paramType.containsOpaque() ||
2750 (paramType.getBasicType() == glslang::EbtBlock && paramType.getQualifier().storage == glslang::EvqBuffer))
Jason Ekstranded15ef12016-06-08 13:54:48 -07002751 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2752 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002753 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2754 else
John Kessenich4bf71552016-09-02 11:20:21 -06002755 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002756 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002757 paramTypes.push_back(typeId);
2758 }
2759
2760 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002761 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2762 convertGlslangToSpvType(glslFunction->getType()),
2763 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002764
2765 // Track function to emit/call later
2766 functionMap[glslFunction->getName().c_str()] = function;
2767
2768 // Set the parameter id's
2769 for (int p = 0; p < (int)parameters.size(); ++p) {
2770 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2771 // give a name too
2772 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2773 }
2774 }
2775}
2776
2777// Process all the initializers, while skipping the functions and link objects
2778void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2779{
2780 builder.setBuildPoint(shaderEntry->getLastBlock());
2781 for (int i = 0; i < (int)initializers.size(); ++i) {
2782 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2783 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2784
2785 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002786 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002787 initializer->traverse(this);
2788 }
2789 }
2790}
2791
2792// Process all the functions, while skipping initializers.
2793void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2794{
2795 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2796 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002797 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002798 node->traverse(this);
2799 }
2800}
2801
2802void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2803{
qining25262b32016-05-06 17:25:16 -04002804 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002805 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002806 currentFunction = functionMap[node->getName().c_str()];
2807 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002808 builder.setBuildPoint(functionBlock);
2809}
2810
Rex Xu04db3f52015-09-16 11:44:02 +08002811void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002812{
Rex Xufc618912015-09-09 16:42:49 +08002813 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002814
2815 glslang::TSampler sampler = {};
2816 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002817 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002818 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2819 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2820 }
2821
John Kessenich140f3df2015-06-26 16:58:36 -06002822 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2823 builder.clearAccessChain();
2824 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002825
2826 // Special case l-value operands
2827 bool lvalue = false;
2828 switch (node.getOp()) {
2829 case glslang::EOpImageAtomicAdd:
2830 case glslang::EOpImageAtomicMin:
2831 case glslang::EOpImageAtomicMax:
2832 case glslang::EOpImageAtomicAnd:
2833 case glslang::EOpImageAtomicOr:
2834 case glslang::EOpImageAtomicXor:
2835 case glslang::EOpImageAtomicExchange:
2836 case glslang::EOpImageAtomicCompSwap:
2837 if (i == 0)
2838 lvalue = true;
2839 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002840 case glslang::EOpSparseImageLoad:
2841 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2842 lvalue = true;
2843 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002844 case glslang::EOpSparseTexture:
2845 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2846 lvalue = true;
2847 break;
2848 case glslang::EOpSparseTextureClamp:
2849 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2850 lvalue = true;
2851 break;
2852 case glslang::EOpSparseTextureLod:
2853 case glslang::EOpSparseTextureOffset:
2854 if (i == 3)
2855 lvalue = true;
2856 break;
2857 case glslang::EOpSparseTextureFetch:
2858 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2859 lvalue = true;
2860 break;
2861 case glslang::EOpSparseTextureFetchOffset:
2862 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2863 lvalue = true;
2864 break;
2865 case glslang::EOpSparseTextureLodOffset:
2866 case glslang::EOpSparseTextureGrad:
2867 case glslang::EOpSparseTextureOffsetClamp:
2868 if (i == 4)
2869 lvalue = true;
2870 break;
2871 case glslang::EOpSparseTextureGradOffset:
2872 case glslang::EOpSparseTextureGradClamp:
2873 if (i == 5)
2874 lvalue = true;
2875 break;
2876 case glslang::EOpSparseTextureGradOffsetClamp:
2877 if (i == 6)
2878 lvalue = true;
2879 break;
2880 case glslang::EOpSparseTextureGather:
2881 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2882 lvalue = true;
2883 break;
2884 case glslang::EOpSparseTextureGatherOffset:
2885 case glslang::EOpSparseTextureGatherOffsets:
2886 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2887 lvalue = true;
2888 break;
Rex Xufc618912015-09-09 16:42:49 +08002889 default:
2890 break;
2891 }
2892
Rex Xu6b86d492015-09-16 17:48:22 +08002893 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002894 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002895 else
John Kessenich32cfd492016-02-02 12:37:46 -07002896 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002897 }
2898}
2899
John Kessenichfc51d282015-08-19 13:34:18 -06002900void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002901{
John Kessenichfc51d282015-08-19 13:34:18 -06002902 builder.clearAccessChain();
2903 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002904 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002905}
John Kessenich140f3df2015-06-26 16:58:36 -06002906
John Kessenichfc51d282015-08-19 13:34:18 -06002907spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2908{
Rex Xufc618912015-09-09 16:42:49 +08002909 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002910 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002911 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002912 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002913
John Kessenichfc51d282015-08-19 13:34:18 -06002914 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002915 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2916 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2917 std::vector<spv::Id> arguments;
2918 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002919 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002920 else
2921 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002922 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002923
2924 spv::Builder::TextureParameters params = { };
2925 params.sampler = arguments[0];
2926
Rex Xu04db3f52015-09-16 11:44:02 +08002927 glslang::TCrackedTextureOp cracked;
2928 node->crackTexture(sampler, cracked);
2929
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002930 const bool isUnsignedResult =
2931 node->getType().getBasicType() == glslang::EbtUint64 ||
2932 node->getType().getBasicType() == glslang::EbtUint;
2933
John Kessenichfc51d282015-08-19 13:34:18 -06002934 // Check for queries
2935 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002936 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2937 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002938 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002939
John Kessenichfc51d282015-08-19 13:34:18 -06002940 switch (node->getOp()) {
2941 case glslang::EOpImageQuerySize:
2942 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002943 if (arguments.size() > 1) {
2944 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002945 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002946 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002947 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002948 case glslang::EOpImageQuerySamples:
2949 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002950 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002951 case glslang::EOpTextureQueryLod:
2952 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002953 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002954 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002955 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08002956 case glslang::EOpSparseTexelsResident:
2957 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002958 default:
2959 assert(0);
2960 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002961 }
John Kessenich140f3df2015-06-26 16:58:36 -06002962 }
2963
Rex Xufc618912015-09-09 16:42:49 +08002964 // Check for image functions other than queries
2965 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002966 std::vector<spv::Id> operands;
2967 auto opIt = arguments.begin();
2968 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002969
2970 // Handle subpass operations
2971 // TODO: GLSL should change to have the "MS" only on the type rather than the
2972 // built-in function.
2973 if (cracked.subpass) {
2974 // add on the (0,0) coordinate
2975 spv::Id zero = builder.makeIntConstant(0);
2976 std::vector<spv::Id> comps;
2977 comps.push_back(zero);
2978 comps.push_back(zero);
2979 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2980 if (sampler.ms) {
2981 operands.push_back(spv::ImageOperandsSampleMask);
2982 operands.push_back(*(opIt++));
2983 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002984 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002985 }
2986
John Kessenich56bab042015-09-16 10:54:31 -06002987 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002988 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002989 if (sampler.ms) {
2990 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002991 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002992 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002993 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2994 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002995 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002996 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002997 if (sampler.ms) {
2998 operands.push_back(*(opIt + 1));
2999 operands.push_back(spv::ImageOperandsSampleMask);
3000 operands.push_back(*opIt);
3001 } else
3002 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003003 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003004 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3005 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003006 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003007 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3008 builder.addCapability(spv::CapabilitySparseResidency);
3009 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3010 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3011
3012 if (sampler.ms) {
3013 operands.push_back(spv::ImageOperandsSampleMask);
3014 operands.push_back(*opIt++);
3015 }
3016
3017 // Create the return type that was a special structure
3018 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003019 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003020 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3021 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3022
3023 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3024
3025 // Decode the return type
3026 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3027 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003028 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003029 // Process image atomic operations
3030
3031 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3032 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003033 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003034
John Kessenich8c8505c2016-07-26 12:50:38 -06003035 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003036 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003037
3038 std::vector<spv::Id> operands;
3039 operands.push_back(pointer);
3040 for (; opIt != arguments.end(); ++opIt)
3041 operands.push_back(*opIt);
3042
John Kessenich8c8505c2016-07-26 12:50:38 -06003043 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003044 }
3045 }
3046
3047 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003048 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003049 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3050
John Kessenichfc51d282015-08-19 13:34:18 -06003051 // check for bias argument
3052 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003053 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003054 int nonBiasArgCount = 2;
3055 if (cracked.offset)
3056 ++nonBiasArgCount;
3057 if (cracked.grad)
3058 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003059 if (cracked.lodClamp)
3060 ++nonBiasArgCount;
3061 if (sparse)
3062 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003063
3064 if ((int)arguments.size() > nonBiasArgCount)
3065 bias = true;
3066 }
3067
John Kessenicha5c33d62016-06-02 23:45:21 -06003068 // See if the sampler param should really be just the SPV image part
3069 if (cracked.fetch) {
3070 // a fetch needs to have the image extracted first
3071 if (builder.isSampledImage(params.sampler))
3072 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3073 }
3074
John Kessenichfc51d282015-08-19 13:34:18 -06003075 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003076
John Kessenichfc51d282015-08-19 13:34:18 -06003077 params.coords = arguments[1];
3078 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003079 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003080
3081 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003082 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003083 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003084 ++extraArgs;
3085 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003086 params.Dref = arguments[2];
3087 ++extraArgs;
3088 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003089 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003090 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003091 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003092 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003093 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003094 dRefComp = builder.getNumComponents(params.coords) - 1;
3095 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003096 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3097 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003098
3099 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003100 if (cracked.lod) {
3101 params.lod = arguments[2];
3102 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003103 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3104 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3105 noImplicitLod = true;
3106 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003107
3108 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003109 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003110 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003111 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003112 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003113
3114 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003115 if (cracked.grad) {
3116 params.gradX = arguments[2 + extraArgs];
3117 params.gradY = arguments[3 + extraArgs];
3118 extraArgs += 2;
3119 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003120
3121 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003122 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003123 params.offset = arguments[2 + extraArgs];
3124 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003125 } else if (cracked.offsets) {
3126 params.offsets = arguments[2 + extraArgs];
3127 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003128 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003129
3130 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003131 if (cracked.lodClamp) {
3132 params.lodClamp = arguments[2 + extraArgs];
3133 ++extraArgs;
3134 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003135
3136 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003137 if (sparse) {
3138 params.texelOut = arguments[2 + extraArgs];
3139 ++extraArgs;
3140 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003141
3142 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003143 if (bias) {
3144 params.bias = arguments[2 + extraArgs];
3145 ++extraArgs;
3146 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003147
3148 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003149 if (cracked.gather && ! sampler.shadow) {
3150 // default component is 0, if missing, otherwise an argument
3151 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003152 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003153 ++extraArgs;
3154 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003155 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003156 }
3157 }
John Kessenichfc51d282015-08-19 13:34:18 -06003158
John Kessenich65336482016-06-16 14:06:26 -06003159 // projective component (might not to move)
3160 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3161 // are divided by the last component of P."
3162 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3163 // unused components will appear after all used components."
3164 if (cracked.proj) {
3165 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3166 int projTargetComp;
3167 switch (sampler.dim) {
3168 case glslang::Esd1D: projTargetComp = 1; break;
3169 case glslang::Esd2D: projTargetComp = 2; break;
3170 case glslang::EsdRect: projTargetComp = 2; break;
3171 default: projTargetComp = projSourceComp; break;
3172 }
3173 // copy the projective coordinate if we have to
3174 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003175 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003176 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3177 projSourceComp);
3178 params.coords = builder.createCompositeInsert(projComp, params.coords,
3179 builder.getTypeId(params.coords), projTargetComp);
3180 }
3181 }
3182
John Kessenich8c8505c2016-07-26 12:50:38 -06003183 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003184}
3185
3186spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3187{
3188 // Grab the function's pointer from the previously created function
3189 spv::Function* function = functionMap[node->getName().c_str()];
3190 if (! function)
3191 return 0;
3192
3193 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3194 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3195
3196 // See comments in makeFunctions() for details about the semantics for parameter passing.
3197 //
3198 // These imply we need a four step process:
3199 // 1. Evaluate the arguments
3200 // 2. Allocate and make copies of in, out, and inout arguments
3201 // 3. Make the call
3202 // 4. Copy back the results
3203
3204 // 1. Evaluate the arguments
3205 std::vector<spv::Builder::AccessChain> lValues;
3206 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003207 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003208 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003209 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003210 // build l-value
3211 builder.clearAccessChain();
3212 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003213 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003214 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003215 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003216 // save l-value
3217 lValues.push_back(builder.getAccessChain());
3218 } else {
3219 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003220 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003221 }
3222 }
3223
3224 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3225 // copy the original into that space.
3226 //
3227 // Also, build up the list of actual arguments to pass in for the call
3228 int lValueCount = 0;
3229 int rValueCount = 0;
3230 std::vector<spv::Id> spvArgs;
3231 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003232 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003233 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003234 if (paramType.containsOpaque() ||
3235 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003236 builder.setAccessChain(lValues[lValueCount]);
3237 arg = builder.accessChainGetLValue();
3238 ++lValueCount;
3239 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003240 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003241 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3242 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3243 // need to copy the input into output space
3244 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003245 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003246 builder.clearAccessChain();
3247 builder.setAccessChainLValue(arg);
3248 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 }
3250 ++lValueCount;
3251 } else {
3252 arg = rValues[rValueCount];
3253 ++rValueCount;
3254 }
3255 spvArgs.push_back(arg);
3256 }
3257
3258 // 3. Make the call.
3259 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003260 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003261
3262 // 4. Copy back out an "out" arguments.
3263 lValueCount = 0;
3264 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003265 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003266 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3267 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3268 spv::Id copy = builder.createLoad(spvArgs[a]);
3269 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003270 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003271 }
3272 ++lValueCount;
3273 }
3274 }
3275
3276 return result;
3277}
3278
3279// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003280spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3281 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003282 spv::Id typeId, spv::Id left, spv::Id right,
3283 glslang::TBasicType typeProxy, bool reduceComparison)
3284{
Rex Xu8ff43de2016-04-22 16:51:45 +08003285 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003286#ifdef AMD_EXTENSIONS
3287 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3288#else
John Kessenich140f3df2015-06-26 16:58:36 -06003289 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003290#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003291 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003292
3293 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003294 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003295 bool comparison = false;
3296
3297 switch (op) {
3298 case glslang::EOpAdd:
3299 case glslang::EOpAddAssign:
3300 if (isFloat)
3301 binOp = spv::OpFAdd;
3302 else
3303 binOp = spv::OpIAdd;
3304 break;
3305 case glslang::EOpSub:
3306 case glslang::EOpSubAssign:
3307 if (isFloat)
3308 binOp = spv::OpFSub;
3309 else
3310 binOp = spv::OpISub;
3311 break;
3312 case glslang::EOpMul:
3313 case glslang::EOpMulAssign:
3314 if (isFloat)
3315 binOp = spv::OpFMul;
3316 else
3317 binOp = spv::OpIMul;
3318 break;
3319 case glslang::EOpVectorTimesScalar:
3320 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003321 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003322 if (builder.isVector(right))
3323 std::swap(left, right);
3324 assert(builder.isScalar(right));
3325 needMatchingVectors = false;
3326 binOp = spv::OpVectorTimesScalar;
3327 } else
3328 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003329 break;
3330 case glslang::EOpVectorTimesMatrix:
3331 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003332 binOp = spv::OpVectorTimesMatrix;
3333 break;
3334 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003335 binOp = spv::OpMatrixTimesVector;
3336 break;
3337 case glslang::EOpMatrixTimesScalar:
3338 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003339 binOp = spv::OpMatrixTimesScalar;
3340 break;
3341 case glslang::EOpMatrixTimesMatrix:
3342 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003343 binOp = spv::OpMatrixTimesMatrix;
3344 break;
3345 case glslang::EOpOuterProduct:
3346 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003347 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349
3350 case glslang::EOpDiv:
3351 case glslang::EOpDivAssign:
3352 if (isFloat)
3353 binOp = spv::OpFDiv;
3354 else if (isUnsigned)
3355 binOp = spv::OpUDiv;
3356 else
3357 binOp = spv::OpSDiv;
3358 break;
3359 case glslang::EOpMod:
3360 case glslang::EOpModAssign:
3361 if (isFloat)
3362 binOp = spv::OpFMod;
3363 else if (isUnsigned)
3364 binOp = spv::OpUMod;
3365 else
3366 binOp = spv::OpSMod;
3367 break;
3368 case glslang::EOpRightShift:
3369 case glslang::EOpRightShiftAssign:
3370 if (isUnsigned)
3371 binOp = spv::OpShiftRightLogical;
3372 else
3373 binOp = spv::OpShiftRightArithmetic;
3374 break;
3375 case glslang::EOpLeftShift:
3376 case glslang::EOpLeftShiftAssign:
3377 binOp = spv::OpShiftLeftLogical;
3378 break;
3379 case glslang::EOpAnd:
3380 case glslang::EOpAndAssign:
3381 binOp = spv::OpBitwiseAnd;
3382 break;
3383 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003384 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003385 binOp = spv::OpLogicalAnd;
3386 break;
3387 case glslang::EOpInclusiveOr:
3388 case glslang::EOpInclusiveOrAssign:
3389 binOp = spv::OpBitwiseOr;
3390 break;
3391 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003392 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003393 binOp = spv::OpLogicalOr;
3394 break;
3395 case glslang::EOpExclusiveOr:
3396 case glslang::EOpExclusiveOrAssign:
3397 binOp = spv::OpBitwiseXor;
3398 break;
3399 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003400 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003401 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003402 break;
3403
3404 case glslang::EOpLessThan:
3405 case glslang::EOpGreaterThan:
3406 case glslang::EOpLessThanEqual:
3407 case glslang::EOpGreaterThanEqual:
3408 case glslang::EOpEqual:
3409 case glslang::EOpNotEqual:
3410 case glslang::EOpVectorEqual:
3411 case glslang::EOpVectorNotEqual:
3412 comparison = true;
3413 break;
3414 default:
3415 break;
3416 }
3417
John Kessenich7c1aa102015-10-15 13:29:11 -06003418 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003419 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003420 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003421 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003422 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003423
3424 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003425 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003426 builder.promoteScalar(precision, left, right);
3427
qining25262b32016-05-06 17:25:16 -04003428 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3429 addDecoration(result, noContraction);
3430 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003431 }
3432
3433 if (! comparison)
3434 return 0;
3435
John Kessenich7c1aa102015-10-15 13:29:11 -06003436 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003437
John Kessenich4583b612016-08-07 19:14:22 -06003438 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3439 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003440 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003441
3442 switch (op) {
3443 case glslang::EOpLessThan:
3444 if (isFloat)
3445 binOp = spv::OpFOrdLessThan;
3446 else if (isUnsigned)
3447 binOp = spv::OpULessThan;
3448 else
3449 binOp = spv::OpSLessThan;
3450 break;
3451 case glslang::EOpGreaterThan:
3452 if (isFloat)
3453 binOp = spv::OpFOrdGreaterThan;
3454 else if (isUnsigned)
3455 binOp = spv::OpUGreaterThan;
3456 else
3457 binOp = spv::OpSGreaterThan;
3458 break;
3459 case glslang::EOpLessThanEqual:
3460 if (isFloat)
3461 binOp = spv::OpFOrdLessThanEqual;
3462 else if (isUnsigned)
3463 binOp = spv::OpULessThanEqual;
3464 else
3465 binOp = spv::OpSLessThanEqual;
3466 break;
3467 case glslang::EOpGreaterThanEqual:
3468 if (isFloat)
3469 binOp = spv::OpFOrdGreaterThanEqual;
3470 else if (isUnsigned)
3471 binOp = spv::OpUGreaterThanEqual;
3472 else
3473 binOp = spv::OpSGreaterThanEqual;
3474 break;
3475 case glslang::EOpEqual:
3476 case glslang::EOpVectorEqual:
3477 if (isFloat)
3478 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003479 else if (isBool)
3480 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003481 else
3482 binOp = spv::OpIEqual;
3483 break;
3484 case glslang::EOpNotEqual:
3485 case glslang::EOpVectorNotEqual:
3486 if (isFloat)
3487 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003488 else if (isBool)
3489 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003490 else
3491 binOp = spv::OpINotEqual;
3492 break;
3493 default:
3494 break;
3495 }
3496
qining25262b32016-05-06 17:25:16 -04003497 if (binOp != spv::OpNop) {
3498 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3499 addDecoration(result, noContraction);
3500 return builder.setPrecision(result, precision);
3501 }
John Kessenich140f3df2015-06-26 16:58:36 -06003502
3503 return 0;
3504}
3505
John Kessenich04bb8a02015-12-12 12:28:14 -07003506//
3507// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3508// These can be any of:
3509//
3510// matrix * scalar
3511// scalar * matrix
3512// matrix * matrix linear algebraic
3513// matrix * vector
3514// vector * matrix
3515// matrix * matrix componentwise
3516// matrix op matrix op in {+, -, /}
3517// matrix op scalar op in {+, -, /}
3518// scalar op matrix op in {+, -, /}
3519//
qining25262b32016-05-06 17:25:16 -04003520spv::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 -07003521{
3522 bool firstClass = true;
3523
3524 // First, handle first-class matrix operations (* and matrix/scalar)
3525 switch (op) {
3526 case spv::OpFDiv:
3527 if (builder.isMatrix(left) && builder.isScalar(right)) {
3528 // turn matrix / scalar into a multiply...
3529 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3530 op = spv::OpMatrixTimesScalar;
3531 } else
3532 firstClass = false;
3533 break;
3534 case spv::OpMatrixTimesScalar:
3535 if (builder.isMatrix(right))
3536 std::swap(left, right);
3537 assert(builder.isScalar(right));
3538 break;
3539 case spv::OpVectorTimesMatrix:
3540 assert(builder.isVector(left));
3541 assert(builder.isMatrix(right));
3542 break;
3543 case spv::OpMatrixTimesVector:
3544 assert(builder.isMatrix(left));
3545 assert(builder.isVector(right));
3546 break;
3547 case spv::OpMatrixTimesMatrix:
3548 assert(builder.isMatrix(left));
3549 assert(builder.isMatrix(right));
3550 break;
3551 default:
3552 firstClass = false;
3553 break;
3554 }
3555
qining25262b32016-05-06 17:25:16 -04003556 if (firstClass) {
3557 spv::Id result = builder.createBinOp(op, typeId, left, right);
3558 addDecoration(result, noContraction);
3559 return builder.setPrecision(result, precision);
3560 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003561
LoopDawg592860c2016-06-09 08:57:35 -06003562 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003563 // The result type of all of them is the same type as the (a) matrix operand.
3564 // The algorithm is to:
3565 // - break the matrix(es) into vectors
3566 // - smear any scalar to a vector
3567 // - do vector operations
3568 // - make a matrix out the vector results
3569 switch (op) {
3570 case spv::OpFAdd:
3571 case spv::OpFSub:
3572 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003573 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003574 case spv::OpFMul:
3575 {
3576 // one time set up...
3577 bool leftMat = builder.isMatrix(left);
3578 bool rightMat = builder.isMatrix(right);
3579 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3580 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3581 spv::Id scalarType = builder.getScalarTypeId(typeId);
3582 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3583 std::vector<spv::Id> results;
3584 spv::Id smearVec = spv::NoResult;
3585 if (builder.isScalar(left))
3586 smearVec = builder.smearScalar(precision, left, vecType);
3587 else if (builder.isScalar(right))
3588 smearVec = builder.smearScalar(precision, right, vecType);
3589
3590 // do each vector op
3591 for (unsigned int c = 0; c < numCols; ++c) {
3592 std::vector<unsigned int> indexes;
3593 indexes.push_back(c);
3594 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3595 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003596 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3597 addDecoration(result, noContraction);
3598 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003599 }
3600
3601 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003602 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003603 }
3604 default:
3605 assert(0);
3606 return spv::NoResult;
3607 }
3608}
3609
qining25262b32016-05-06 17:25:16 -04003610spv::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 -06003611{
3612 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003613 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003615 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003616#ifdef AMD_EXTENSIONS
3617 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3618#else
Rex Xu04db3f52015-09-16 11:44:02 +08003619 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003620#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003621
3622 switch (op) {
3623 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003624 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003625 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003626 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003627 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003628 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003629 unaryOp = spv::OpSNegate;
3630 break;
3631
3632 case glslang::EOpLogicalNot:
3633 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003634 unaryOp = spv::OpLogicalNot;
3635 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003636 case glslang::EOpBitwiseNot:
3637 unaryOp = spv::OpNot;
3638 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003639
John Kessenich140f3df2015-06-26 16:58:36 -06003640 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003641 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003642 break;
3643 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003644 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003645 break;
3646 case glslang::EOpTranspose:
3647 unaryOp = spv::OpTranspose;
3648 break;
3649
3650 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003651 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003652 break;
3653 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003654 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
3656 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003657 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 break;
3659 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003661 break;
3662 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003663 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003664 break;
3665 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003666 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003667 break;
3668 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003669 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003670 break;
3671 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003672 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003673 break;
3674
3675 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003677 break;
3678 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003679 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003682 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003683 break;
3684 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003685 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003686 break;
3687 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003688 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003689 break;
3690 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003691 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003692 break;
3693
3694 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003695 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003696 break;
3697 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003698 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700
3701 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003711 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003714 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
3716 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003717 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003718 break;
3719
3720 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 break;
3726 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003727 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003733 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003736 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003737 break;
3738
3739 case glslang::EOpIsNan:
3740 unaryOp = spv::OpIsNan;
3741 break;
3742 case glslang::EOpIsInf:
3743 unaryOp = spv::OpIsInf;
3744 break;
LoopDawg592860c2016-06-09 08:57:35 -06003745 case glslang::EOpIsFinite:
3746 unaryOp = spv::OpIsFinite;
3747 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003748
Rex Xucbc426e2015-12-15 16:03:10 +08003749 case glslang::EOpFloatBitsToInt:
3750 case glslang::EOpFloatBitsToUint:
3751 case glslang::EOpIntBitsToFloat:
3752 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003753 case glslang::EOpDoubleBitsToInt64:
3754 case glslang::EOpDoubleBitsToUint64:
3755 case glslang::EOpInt64BitsToDouble:
3756 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003757 unaryOp = spv::OpBitcast;
3758 break;
3759
John Kessenich140f3df2015-06-26 16:58:36 -06003760 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
3769 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003778 case glslang::EOpPackSnorm4x8:
3779 libCall = spv::GLSLstd450PackSnorm4x8;
3780 break;
3781 case glslang::EOpUnpackSnorm4x8:
3782 libCall = spv::GLSLstd450UnpackSnorm4x8;
3783 break;
3784 case glslang::EOpPackUnorm4x8:
3785 libCall = spv::GLSLstd450PackUnorm4x8;
3786 break;
3787 case glslang::EOpUnpackUnorm4x8:
3788 libCall = spv::GLSLstd450UnpackUnorm4x8;
3789 break;
3790 case glslang::EOpPackDouble2x32:
3791 libCall = spv::GLSLstd450PackDouble2x32;
3792 break;
3793 case glslang::EOpUnpackDouble2x32:
3794 libCall = spv::GLSLstd450UnpackDouble2x32;
3795 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003796
Rex Xu8ff43de2016-04-22 16:51:45 +08003797 case glslang::EOpPackInt2x32:
3798 case glslang::EOpUnpackInt2x32:
3799 case glslang::EOpPackUint2x32:
3800 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003801 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003802 break;
3803
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003804#ifdef AMD_EXTENSIONS
3805 case glslang::EOpPackFloat2x16:
3806 case glslang::EOpUnpackFloat2x16:
3807 unaryOp = spv::OpBitcast;
3808 break;
3809#endif
3810
John Kessenich140f3df2015-06-26 16:58:36 -06003811 case glslang::EOpDPdx:
3812 unaryOp = spv::OpDPdx;
3813 break;
3814 case glslang::EOpDPdy:
3815 unaryOp = spv::OpDPdy;
3816 break;
3817 case glslang::EOpFwidth:
3818 unaryOp = spv::OpFwidth;
3819 break;
3820 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003821 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003822 unaryOp = spv::OpDPdxFine;
3823 break;
3824 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003825 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003826 unaryOp = spv::OpDPdyFine;
3827 break;
3828 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003829 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003830 unaryOp = spv::OpFwidthFine;
3831 break;
3832 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003833 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003834 unaryOp = spv::OpDPdxCoarse;
3835 break;
3836 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003837 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 unaryOp = spv::OpDPdyCoarse;
3839 break;
3840 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003841 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003842 unaryOp = spv::OpFwidthCoarse;
3843 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003844 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003845 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003846 libCall = spv::GLSLstd450InterpolateAtCentroid;
3847 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003848 case glslang::EOpAny:
3849 unaryOp = spv::OpAny;
3850 break;
3851 case glslang::EOpAll:
3852 unaryOp = spv::OpAll;
3853 break;
3854
3855 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003856 if (isFloat)
3857 libCall = spv::GLSLstd450FAbs;
3858 else
3859 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003860 break;
3861 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003862 if (isFloat)
3863 libCall = spv::GLSLstd450FSign;
3864 else
3865 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003866 break;
3867
John Kessenichfc51d282015-08-19 13:34:18 -06003868 case glslang::EOpAtomicCounterIncrement:
3869 case glslang::EOpAtomicCounterDecrement:
3870 case glslang::EOpAtomicCounter:
3871 {
3872 // Handle all of the atomics in one place, in createAtomicOperation()
3873 std::vector<spv::Id> operands;
3874 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003875 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003876 }
3877
John Kessenichfc51d282015-08-19 13:34:18 -06003878 case glslang::EOpBitFieldReverse:
3879 unaryOp = spv::OpBitReverse;
3880 break;
3881 case glslang::EOpBitCount:
3882 unaryOp = spv::OpBitCount;
3883 break;
3884 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003885 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003886 break;
3887 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003888 if (isUnsigned)
3889 libCall = spv::GLSLstd450FindUMsb;
3890 else
3891 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003892 break;
3893
Rex Xu574ab042016-04-14 16:53:07 +08003894 case glslang::EOpBallot:
3895 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003896 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003897 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003898 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003899#ifdef AMD_EXTENSIONS
3900 case glslang::EOpMinInvocations:
3901 case glslang::EOpMaxInvocations:
3902 case glslang::EOpAddInvocations:
3903 case glslang::EOpMinInvocationsNonUniform:
3904 case glslang::EOpMaxInvocationsNonUniform:
3905 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003906 case glslang::EOpMinInvocationsInclusiveScan:
3907 case glslang::EOpMaxInvocationsInclusiveScan:
3908 case glslang::EOpAddInvocationsInclusiveScan:
3909 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3910 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3911 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3912 case glslang::EOpMinInvocationsExclusiveScan:
3913 case glslang::EOpMaxInvocationsExclusiveScan:
3914 case glslang::EOpAddInvocationsExclusiveScan:
3915 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3916 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3917 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003918#endif
Rex Xu51596642016-09-21 18:56:12 +08003919 {
3920 std::vector<spv::Id> operands;
3921 operands.push_back(operand);
3922 return createInvocationsOperation(op, typeId, operands, typeProxy);
3923 }
Rex Xu9d93a232016-05-05 12:30:44 +08003924
3925#ifdef AMD_EXTENSIONS
3926 case glslang::EOpMbcnt:
3927 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3928 libCall = spv::MbcntAMD;
3929 break;
3930
3931 case glslang::EOpCubeFaceIndex:
3932 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3933 libCall = spv::CubeFaceIndexAMD;
3934 break;
3935
3936 case glslang::EOpCubeFaceCoord:
3937 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3938 libCall = spv::CubeFaceCoordAMD;
3939 break;
3940#endif
Rex Xu338b1852016-05-05 20:38:33 +08003941
John Kessenich140f3df2015-06-26 16:58:36 -06003942 default:
3943 return 0;
3944 }
3945
3946 spv::Id id;
3947 if (libCall >= 0) {
3948 std::vector<spv::Id> args;
3949 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003950 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003951 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003952 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003953 }
John Kessenich140f3df2015-06-26 16:58:36 -06003954
qining25262b32016-05-06 17:25:16 -04003955 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003956 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003957}
3958
John Kessenich7a53f762016-01-20 11:19:27 -07003959// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003960spv::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 -07003961{
3962 // Handle unary operations vector by vector.
3963 // The result type is the same type as the original type.
3964 // The algorithm is to:
3965 // - break the matrix into vectors
3966 // - apply the operation to each vector
3967 // - make a matrix out the vector results
3968
3969 // get the types sorted out
3970 int numCols = builder.getNumColumns(operand);
3971 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003972 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3973 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003974 std::vector<spv::Id> results;
3975
3976 // do each vector op
3977 for (int c = 0; c < numCols; ++c) {
3978 std::vector<unsigned int> indexes;
3979 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003980 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3981 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3982 addDecoration(destVec, noContraction);
3983 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003984 }
3985
3986 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003987 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003988}
3989
Rex Xu73e3ce72016-04-27 18:48:17 +08003990spv::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 -06003991{
3992 spv::Op convOp = spv::OpNop;
3993 spv::Id zero = 0;
3994 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003995 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003996
3997 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3998
3999 switch (op) {
4000 case glslang::EOpConvIntToBool:
4001 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004002 case glslang::EOpConvInt64ToBool:
4003 case glslang::EOpConvUint64ToBool:
4004 zero = (op == glslang::EOpConvInt64ToBool ||
4005 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004006 zero = makeSmearedConstant(zero, vectorSize);
4007 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4008
4009 case glslang::EOpConvFloatToBool:
4010 zero = builder.makeFloatConstant(0.0F);
4011 zero = makeSmearedConstant(zero, vectorSize);
4012 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4013
4014 case glslang::EOpConvDoubleToBool:
4015 zero = builder.makeDoubleConstant(0.0);
4016 zero = makeSmearedConstant(zero, vectorSize);
4017 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4018
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004019#ifdef AMD_EXTENSIONS
4020 case glslang::EOpConvFloat16ToBool:
4021 zero = builder.makeFloat16Constant(0.0F);
4022 zero = makeSmearedConstant(zero, vectorSize);
4023 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4024#endif
4025
John Kessenich140f3df2015-06-26 16:58:36 -06004026 case glslang::EOpConvBoolToFloat:
4027 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004028 zero = builder.makeFloatConstant(0.0F);
4029 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004030 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004031
John Kessenich140f3df2015-06-26 16:58:36 -06004032 case glslang::EOpConvBoolToDouble:
4033 convOp = spv::OpSelect;
4034 zero = builder.makeDoubleConstant(0.0);
4035 one = builder.makeDoubleConstant(1.0);
4036 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004037
4038#ifdef AMD_EXTENSIONS
4039 case glslang::EOpConvBoolToFloat16:
4040 convOp = spv::OpSelect;
4041 zero = builder.makeFloat16Constant(0.0F);
4042 one = builder.makeFloat16Constant(1.0F);
4043 break;
4044#endif
4045
John Kessenich140f3df2015-06-26 16:58:36 -06004046 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004047 case glslang::EOpConvBoolToInt64:
4048 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4049 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004050 convOp = spv::OpSelect;
4051 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004052
John Kessenich140f3df2015-06-26 16:58:36 -06004053 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004054 case glslang::EOpConvBoolToUint64:
4055 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4056 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004057 convOp = spv::OpSelect;
4058 break;
4059
4060 case glslang::EOpConvIntToFloat:
4061 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004062 case glslang::EOpConvInt64ToFloat:
4063 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004064#ifdef AMD_EXTENSIONS
4065 case glslang::EOpConvIntToFloat16:
4066 case glslang::EOpConvInt64ToFloat16:
4067#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004068 convOp = spv::OpConvertSToF;
4069 break;
4070
4071 case glslang::EOpConvUintToFloat:
4072 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004073 case glslang::EOpConvUint64ToFloat:
4074 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004075#ifdef AMD_EXTENSIONS
4076 case glslang::EOpConvUintToFloat16:
4077 case glslang::EOpConvUint64ToFloat16:
4078#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004079 convOp = spv::OpConvertUToF;
4080 break;
4081
4082 case glslang::EOpConvDoubleToFloat:
4083 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004084#ifdef AMD_EXTENSIONS
4085 case glslang::EOpConvDoubleToFloat16:
4086 case glslang::EOpConvFloat16ToDouble:
4087 case glslang::EOpConvFloatToFloat16:
4088 case glslang::EOpConvFloat16ToFloat:
4089#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004090 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004091 if (builder.isMatrixType(destType))
4092 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004093 break;
4094
4095 case glslang::EOpConvFloatToInt:
4096 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004097 case glslang::EOpConvFloatToInt64:
4098 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004099#ifdef AMD_EXTENSIONS
4100 case glslang::EOpConvFloat16ToInt:
4101 case glslang::EOpConvFloat16ToInt64:
4102#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004103 convOp = spv::OpConvertFToS;
4104 break;
4105
4106 case glslang::EOpConvUintToInt:
4107 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004108 case glslang::EOpConvUint64ToInt64:
4109 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004110 if (builder.isInSpecConstCodeGenMode()) {
4111 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004112 zero = (op == glslang::EOpConvUint64ToInt64 ||
4113 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004114 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004115 // Use OpIAdd, instead of OpBitcast to do the conversion when
4116 // generating for OpSpecConstantOp instruction.
4117 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4118 }
4119 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004120 convOp = spv::OpBitcast;
4121 break;
4122
4123 case glslang::EOpConvFloatToUint:
4124 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004125 case glslang::EOpConvFloatToUint64:
4126 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004127#ifdef AMD_EXTENSIONS
4128 case glslang::EOpConvFloat16ToUint:
4129 case glslang::EOpConvFloat16ToUint64:
4130#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004131 convOp = spv::OpConvertFToU;
4132 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004133
4134 case glslang::EOpConvIntToInt64:
4135 case glslang::EOpConvInt64ToInt:
4136 convOp = spv::OpSConvert;
4137 break;
4138
4139 case glslang::EOpConvUintToUint64:
4140 case glslang::EOpConvUint64ToUint:
4141 convOp = spv::OpUConvert;
4142 break;
4143
4144 case glslang::EOpConvIntToUint64:
4145 case glslang::EOpConvInt64ToUint:
4146 case glslang::EOpConvUint64ToInt:
4147 case glslang::EOpConvUintToInt64:
4148 // OpSConvert/OpUConvert + OpBitCast
4149 switch (op) {
4150 case glslang::EOpConvIntToUint64:
4151 convOp = spv::OpSConvert;
4152 type = builder.makeIntType(64);
4153 break;
4154 case glslang::EOpConvInt64ToUint:
4155 convOp = spv::OpSConvert;
4156 type = builder.makeIntType(32);
4157 break;
4158 case glslang::EOpConvUint64ToInt:
4159 convOp = spv::OpUConvert;
4160 type = builder.makeUintType(32);
4161 break;
4162 case glslang::EOpConvUintToInt64:
4163 convOp = spv::OpUConvert;
4164 type = builder.makeUintType(64);
4165 break;
4166 default:
4167 assert(0);
4168 break;
4169 }
4170
4171 if (vectorSize > 0)
4172 type = builder.makeVectorType(type, vectorSize);
4173
4174 operand = builder.createUnaryOp(convOp, type, operand);
4175
4176 if (builder.isInSpecConstCodeGenMode()) {
4177 // Build zero scalar or vector for OpIAdd.
4178 zero = (op == glslang::EOpConvIntToUint64 ||
4179 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4180 zero = makeSmearedConstant(zero, vectorSize);
4181 // Use OpIAdd, instead of OpBitcast to do the conversion when
4182 // generating for OpSpecConstantOp instruction.
4183 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4184 }
4185 // For normal run-time conversion instruction, use OpBitcast.
4186 convOp = spv::OpBitcast;
4187 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004188 default:
4189 break;
4190 }
4191
4192 spv::Id result = 0;
4193 if (convOp == spv::OpNop)
4194 return result;
4195
4196 if (convOp == spv::OpSelect) {
4197 zero = makeSmearedConstant(zero, vectorSize);
4198 one = makeSmearedConstant(one, vectorSize);
4199 result = builder.createTriOp(convOp, destType, operand, one, zero);
4200 } else
4201 result = builder.createUnaryOp(convOp, destType, operand);
4202
John Kessenich32cfd492016-02-02 12:37:46 -07004203 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004204}
4205
4206spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4207{
4208 if (vectorSize == 0)
4209 return constant;
4210
4211 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4212 std::vector<spv::Id> components;
4213 for (int c = 0; c < vectorSize; ++c)
4214 components.push_back(constant);
4215 return builder.makeCompositeConstant(vectorTypeId, components);
4216}
4217
John Kessenich426394d2015-07-23 10:22:48 -06004218// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004219spv::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 -06004220{
4221 spv::Op opCode = spv::OpNop;
4222
4223 switch (op) {
4224 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004225 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004226 opCode = spv::OpAtomicIAdd;
4227 break;
4228 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004229 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004230 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004231 break;
4232 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004233 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004234 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004235 break;
4236 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004237 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004238 opCode = spv::OpAtomicAnd;
4239 break;
4240 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004241 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004242 opCode = spv::OpAtomicOr;
4243 break;
4244 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004245 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004246 opCode = spv::OpAtomicXor;
4247 break;
4248 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004249 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004250 opCode = spv::OpAtomicExchange;
4251 break;
4252 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004253 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004254 opCode = spv::OpAtomicCompareExchange;
4255 break;
4256 case glslang::EOpAtomicCounterIncrement:
4257 opCode = spv::OpAtomicIIncrement;
4258 break;
4259 case glslang::EOpAtomicCounterDecrement:
4260 opCode = spv::OpAtomicIDecrement;
4261 break;
4262 case glslang::EOpAtomicCounter:
4263 opCode = spv::OpAtomicLoad;
4264 break;
4265 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004266 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004267 break;
4268 }
4269
4270 // Sort out the operands
4271 // - mapping from glslang -> SPV
4272 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004273 // - compare-exchange swaps the value and comparator
4274 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004275 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4276 auto opIt = operands.begin(); // walk the glslang operands
4277 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004278 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4279 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4280 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004281 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4282 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004283 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004284 spvAtomicOperands.push_back(*(opIt + 1));
4285 spvAtomicOperands.push_back(*opIt);
4286 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004287 }
John Kessenich426394d2015-07-23 10:22:48 -06004288
John Kessenich3e60a6f2015-09-14 22:45:16 -06004289 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004290 for (; opIt != operands.end(); ++opIt)
4291 spvAtomicOperands.push_back(*opIt);
4292
4293 return builder.createOp(opCode, typeId, spvAtomicOperands);
4294}
4295
John Kessenich91cef522016-05-05 16:45:40 -06004296// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004297spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004298{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004299#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004300 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004301 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004302#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004303
Rex Xu51596642016-09-21 18:56:12 +08004304 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004305 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004306 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4307
chaocf200da82016-12-20 12:44:35 -08004308 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4309 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004310 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4311 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004312 } else if (op == glslang::EOpAnyInvocation ||
4313 op == glslang::EOpAllInvocations ||
4314 op == glslang::EOpAllInvocationsEqual) {
4315 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4316 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004317 } else {
4318 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004319#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004320 if (op == glslang::EOpMinInvocationsNonUniform ||
4321 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004322 op == glslang::EOpAddInvocationsNonUniform ||
4323 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4324 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4325 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4326 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4327 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4328 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004329 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004330#endif
Rex Xu51596642016-09-21 18:56:12 +08004331
4332 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004333#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004334 switch (op) {
4335 case glslang::EOpMinInvocations:
4336 case glslang::EOpMaxInvocations:
4337 case glslang::EOpAddInvocations:
4338 case glslang::EOpMinInvocationsNonUniform:
4339 case glslang::EOpMaxInvocationsNonUniform:
4340 case glslang::EOpAddInvocationsNonUniform:
4341 groupOperation = spv::GroupOperationReduce;
4342 spvGroupOperands.push_back(groupOperation);
4343 break;
4344 case glslang::EOpMinInvocationsInclusiveScan:
4345 case glslang::EOpMaxInvocationsInclusiveScan:
4346 case glslang::EOpAddInvocationsInclusiveScan:
4347 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4348 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4349 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4350 groupOperation = spv::GroupOperationInclusiveScan;
4351 spvGroupOperands.push_back(groupOperation);
4352 break;
4353 case glslang::EOpMinInvocationsExclusiveScan:
4354 case glslang::EOpMaxInvocationsExclusiveScan:
4355 case glslang::EOpAddInvocationsExclusiveScan:
4356 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4357 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4358 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4359 groupOperation = spv::GroupOperationExclusiveScan;
4360 spvGroupOperands.push_back(groupOperation);
4361 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004362 default:
4363 break;
Rex Xu430ef402016-10-14 17:22:23 +08004364 }
Rex Xu9d93a232016-05-05 12:30:44 +08004365#endif
Rex Xu51596642016-09-21 18:56:12 +08004366 }
4367
4368 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4369 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004370
4371 switch (op) {
4372 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004373 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004374 break;
John Kessenich91cef522016-05-05 16:45:40 -06004375 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004376 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004377 break;
John Kessenich91cef522016-05-05 16:45:40 -06004378 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004379 opCode = spv::OpSubgroupAllEqualKHR;
4380 break;
Rex Xu51596642016-09-21 18:56:12 +08004381 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004382 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004383 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004384 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004385 break;
4386 case glslang::EOpReadFirstInvocation:
4387 opCode = spv::OpSubgroupFirstInvocationKHR;
4388 break;
4389 case glslang::EOpBallot:
4390 {
4391 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4392 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4393 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4394 //
4395 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4396 //
4397 spv::Id uintType = builder.makeUintType(32);
4398 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4399 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4400
4401 std::vector<spv::Id> components;
4402 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4403 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4404
4405 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4406 return builder.createUnaryOp(spv::OpBitcast, typeId,
4407 builder.createCompositeConstruct(uvec2Type, components));
4408 }
4409
Rex Xu9d93a232016-05-05 12:30:44 +08004410#ifdef AMD_EXTENSIONS
4411 case glslang::EOpMinInvocations:
4412 case glslang::EOpMaxInvocations:
4413 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004414 case glslang::EOpMinInvocationsInclusiveScan:
4415 case glslang::EOpMaxInvocationsInclusiveScan:
4416 case glslang::EOpAddInvocationsInclusiveScan:
4417 case glslang::EOpMinInvocationsExclusiveScan:
4418 case glslang::EOpMaxInvocationsExclusiveScan:
4419 case glslang::EOpAddInvocationsExclusiveScan:
4420 if (op == glslang::EOpMinInvocations ||
4421 op == glslang::EOpMinInvocationsInclusiveScan ||
4422 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004423 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004424 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004425 else {
4426 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004427 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004428 else
Rex Xu51596642016-09-21 18:56:12 +08004429 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004430 }
Rex Xu430ef402016-10-14 17:22:23 +08004431 } else if (op == glslang::EOpMaxInvocations ||
4432 op == glslang::EOpMaxInvocationsInclusiveScan ||
4433 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004434 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004435 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004436 else {
4437 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004438 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004439 else
Rex Xu51596642016-09-21 18:56:12 +08004440 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004441 }
4442 } else {
4443 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004444 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004445 else
Rex Xu51596642016-09-21 18:56:12 +08004446 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004447 }
4448
Rex Xu2bbbe062016-08-23 15:41:05 +08004449 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004450 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004451
4452 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004453 case glslang::EOpMinInvocationsNonUniform:
4454 case glslang::EOpMaxInvocationsNonUniform:
4455 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004456 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4457 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4458 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4459 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4460 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4461 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4462 if (op == glslang::EOpMinInvocationsNonUniform ||
4463 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4464 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004465 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004466 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004467 else {
4468 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004469 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004470 else
Rex Xu51596642016-09-21 18:56:12 +08004471 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004472 }
4473 }
Rex Xu430ef402016-10-14 17:22:23 +08004474 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4475 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4476 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004477 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004478 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004479 else {
4480 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004481 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004482 else
Rex Xu51596642016-09-21 18:56:12 +08004483 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004484 }
4485 }
4486 else {
4487 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004488 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004489 else
Rex Xu51596642016-09-21 18:56:12 +08004490 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004491 }
4492
Rex Xu2bbbe062016-08-23 15:41:05 +08004493 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004494 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004495
4496 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004497#endif
John Kessenich91cef522016-05-05 16:45:40 -06004498 default:
4499 logger->missingFunctionality("invocation operation");
4500 return spv::NoResult;
4501 }
Rex Xu51596642016-09-21 18:56:12 +08004502
4503 assert(opCode != spv::OpNop);
4504 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004505}
4506
Rex Xu2bbbe062016-08-23 15:41:05 +08004507// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004508spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004509{
Rex Xub7072052016-09-26 15:53:40 +08004510#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004511 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4512 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004513 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004514 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004515 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4516 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4517 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004518#else
4519 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4520 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004521 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4522 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004523#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004524
4525 // Handle group invocation operations scalar by scalar.
4526 // The result type is the same type as the original type.
4527 // The algorithm is to:
4528 // - break the vector into scalars
4529 // - apply the operation to each scalar
4530 // - make a vector out the scalar results
4531
4532 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004533 int numComponents = builder.getNumComponents(operands[0]);
4534 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004535 std::vector<spv::Id> results;
4536
4537 // do each scalar op
4538 for (int comp = 0; comp < numComponents; ++comp) {
4539 std::vector<unsigned int> indexes;
4540 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004541 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004542 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004543 if (op == spv::OpSubgroupReadInvocationKHR) {
4544 spvGroupOperands.push_back(scalar);
4545 spvGroupOperands.push_back(operands[1]);
4546 } else if (op == spv::OpGroupBroadcast) {
4547 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004548 spvGroupOperands.push_back(scalar);
4549 spvGroupOperands.push_back(operands[1]);
4550 } else {
chaocf200da82016-12-20 12:44:35 -08004551 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004552 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004553 spvGroupOperands.push_back(scalar);
4554 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004555
Rex Xub7072052016-09-26 15:53:40 +08004556 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004557 }
4558
4559 // put the pieces together
4560 return builder.createCompositeConstruct(typeId, results);
4561}
Rex Xu2bbbe062016-08-23 15:41:05 +08004562
John Kessenich5e4b1242015-08-06 22:53:06 -06004563spv::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 -06004564{
Rex Xu8ff43de2016-04-22 16:51:45 +08004565 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004566#ifdef AMD_EXTENSIONS
4567 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4568#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004569 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004570#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004571
John Kessenich140f3df2015-06-26 16:58:36 -06004572 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004573 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004574 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004575 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004576 spv::Id typeId0 = 0;
4577 if (consumedOperands > 0)
4578 typeId0 = builder.getTypeId(operands[0]);
4579 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004580
4581 switch (op) {
4582 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004583 if (isFloat)
4584 libCall = spv::GLSLstd450FMin;
4585 else if (isUnsigned)
4586 libCall = spv::GLSLstd450UMin;
4587 else
4588 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004589 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004590 break;
4591 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004592 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004593 break;
4594 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004595 if (isFloat)
4596 libCall = spv::GLSLstd450FMax;
4597 else if (isUnsigned)
4598 libCall = spv::GLSLstd450UMax;
4599 else
4600 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004601 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004602 break;
4603 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004604 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004605 break;
4606 case glslang::EOpDot:
4607 opCode = spv::OpDot;
4608 break;
4609 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004610 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004611 break;
4612
4613 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004614 if (isFloat)
4615 libCall = spv::GLSLstd450FClamp;
4616 else if (isUnsigned)
4617 libCall = spv::GLSLstd450UClamp;
4618 else
4619 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004620 builder.promoteScalar(precision, operands.front(), operands[1]);
4621 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004622 break;
4623 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004624 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4625 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004626 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004627 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004628 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004629 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004630 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004631 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004632 break;
4633 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004634 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004635 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004636 break;
4637 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004638 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004639 builder.promoteScalar(precision, operands[0], operands[2]);
4640 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004641 break;
4642
4643 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004644 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004645 break;
4646 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004647 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004648 break;
4649 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004650 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004651 break;
4652 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004653 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004654 break;
4655 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004656 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004657 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004658 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004659 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004660 libCall = spv::GLSLstd450InterpolateAtSample;
4661 break;
4662 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004663 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004664 libCall = spv::GLSLstd450InterpolateAtOffset;
4665 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004666 case glslang::EOpAddCarry:
4667 opCode = spv::OpIAddCarry;
4668 typeId = builder.makeStructResultType(typeId0, typeId0);
4669 consumedOperands = 2;
4670 break;
4671 case glslang::EOpSubBorrow:
4672 opCode = spv::OpISubBorrow;
4673 typeId = builder.makeStructResultType(typeId0, typeId0);
4674 consumedOperands = 2;
4675 break;
4676 case glslang::EOpUMulExtended:
4677 opCode = spv::OpUMulExtended;
4678 typeId = builder.makeStructResultType(typeId0, typeId0);
4679 consumedOperands = 2;
4680 break;
4681 case glslang::EOpIMulExtended:
4682 opCode = spv::OpSMulExtended;
4683 typeId = builder.makeStructResultType(typeId0, typeId0);
4684 consumedOperands = 2;
4685 break;
4686 case glslang::EOpBitfieldExtract:
4687 if (isUnsigned)
4688 opCode = spv::OpBitFieldUExtract;
4689 else
4690 opCode = spv::OpBitFieldSExtract;
4691 break;
4692 case glslang::EOpBitfieldInsert:
4693 opCode = spv::OpBitFieldInsert;
4694 break;
4695
4696 case glslang::EOpFma:
4697 libCall = spv::GLSLstd450Fma;
4698 break;
4699 case glslang::EOpFrexp:
4700 libCall = spv::GLSLstd450FrexpStruct;
4701 if (builder.getNumComponents(operands[0]) == 1)
4702 frexpIntType = builder.makeIntegerType(32, true);
4703 else
4704 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4705 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4706 consumedOperands = 1;
4707 break;
4708 case glslang::EOpLdexp:
4709 libCall = spv::GLSLstd450Ldexp;
4710 break;
4711
Rex Xu574ab042016-04-14 16:53:07 +08004712 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004713 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004714
Rex Xu9d93a232016-05-05 12:30:44 +08004715#ifdef AMD_EXTENSIONS
4716 case glslang::EOpSwizzleInvocations:
4717 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4718 libCall = spv::SwizzleInvocationsAMD;
4719 break;
4720 case glslang::EOpSwizzleInvocationsMasked:
4721 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4722 libCall = spv::SwizzleInvocationsMaskedAMD;
4723 break;
4724 case glslang::EOpWriteInvocation:
4725 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4726 libCall = spv::WriteInvocationAMD;
4727 break;
4728
4729 case glslang::EOpMin3:
4730 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4731 if (isFloat)
4732 libCall = spv::FMin3AMD;
4733 else {
4734 if (isUnsigned)
4735 libCall = spv::UMin3AMD;
4736 else
4737 libCall = spv::SMin3AMD;
4738 }
4739 break;
4740 case glslang::EOpMax3:
4741 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4742 if (isFloat)
4743 libCall = spv::FMax3AMD;
4744 else {
4745 if (isUnsigned)
4746 libCall = spv::UMax3AMD;
4747 else
4748 libCall = spv::SMax3AMD;
4749 }
4750 break;
4751 case glslang::EOpMid3:
4752 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4753 if (isFloat)
4754 libCall = spv::FMid3AMD;
4755 else {
4756 if (isUnsigned)
4757 libCall = spv::UMid3AMD;
4758 else
4759 libCall = spv::SMid3AMD;
4760 }
4761 break;
4762
4763 case glslang::EOpInterpolateAtVertex:
4764 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4765 libCall = spv::InterpolateAtVertexAMD;
4766 break;
4767#endif
4768
John Kessenich140f3df2015-06-26 16:58:36 -06004769 default:
4770 return 0;
4771 }
4772
4773 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004774 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004775 // Use an extended instruction from the standard library.
4776 // Construct the call arguments, without modifying the original operands vector.
4777 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4778 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004779 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004780 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004781 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004782 case 0:
4783 // should all be handled by visitAggregate and createNoArgOperation
4784 assert(0);
4785 return 0;
4786 case 1:
4787 // should all be handled by createUnaryOperation
4788 assert(0);
4789 return 0;
4790 case 2:
4791 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4792 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004793 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004794 // anything 3 or over doesn't have l-value operands, so all should be consumed
4795 assert(consumedOperands == operands.size());
4796 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004797 break;
4798 }
4799 }
4800
John Kessenich55e7d112015-11-15 21:33:39 -07004801 // Decode the return types that were structures
4802 switch (op) {
4803 case glslang::EOpAddCarry:
4804 case glslang::EOpSubBorrow:
4805 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4806 id = builder.createCompositeExtract(id, typeId0, 0);
4807 break;
4808 case glslang::EOpUMulExtended:
4809 case glslang::EOpIMulExtended:
4810 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4811 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4812 break;
4813 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004814 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004815 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4816 id = builder.createCompositeExtract(id, typeId0, 0);
4817 break;
4818 default:
4819 break;
4820 }
4821
John Kessenich32cfd492016-02-02 12:37:46 -07004822 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004823}
4824
Rex Xu9d93a232016-05-05 12:30:44 +08004825// Intrinsics with no arguments (or no return value, and no precision).
4826spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004827{
4828 // TODO: get the barrier operands correct
4829
4830 switch (op) {
4831 case glslang::EOpEmitVertex:
4832 builder.createNoResultOp(spv::OpEmitVertex);
4833 return 0;
4834 case glslang::EOpEndPrimitive:
4835 builder.createNoResultOp(spv::OpEndPrimitive);
4836 return 0;
4837 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004838 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004839 return 0;
4840 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004841 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004842 return 0;
4843 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004844 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004845 return 0;
4846 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004847 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004848 return 0;
4849 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004850 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004851 return 0;
4852 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004853 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004854 return 0;
4855 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004856 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004857 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004858 case glslang::EOpAllMemoryBarrierWithGroupSync:
4859 // Control barrier with non-"None" semantic is also a memory barrier.
4860 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4861 return 0;
4862 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4863 // Control barrier with non-"None" semantic is also a memory barrier.
4864 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4865 return 0;
4866 case glslang::EOpWorkgroupMemoryBarrier:
4867 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4868 return 0;
4869 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4870 // Control barrier with non-"None" semantic is also a memory barrier.
4871 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4872 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004873#ifdef AMD_EXTENSIONS
4874 case glslang::EOpTime:
4875 {
4876 std::vector<spv::Id> args; // Dummy arguments
4877 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4878 return builder.setPrecision(id, precision);
4879 }
4880#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004881 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004882 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004883 return 0;
4884 }
4885}
4886
4887spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4888{
John Kessenich2f273362015-07-18 22:34:27 -06004889 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004890 spv::Id id;
4891 if (symbolValues.end() != iter) {
4892 id = iter->second;
4893 return id;
4894 }
4895
4896 // it was not found, create it
4897 id = createSpvVariable(symbol);
4898 symbolValues[symbol->getId()] = id;
4899
Rex Xuc884b4a2016-06-29 15:03:44 +08004900 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004901 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004902 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004903 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004904 if (symbol->getType().getQualifier().hasSpecConstantId())
4905 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004906 if (symbol->getQualifier().hasIndex())
4907 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4908 if (symbol->getQualifier().hasComponent())
4909 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4910 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004911 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004912 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004913 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004914 if (symbol->getQualifier().hasXfbBuffer())
4915 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4916 if (symbol->getQualifier().hasXfbOffset())
4917 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4918 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004919 // atomic counters use this:
4920 if (symbol->getQualifier().hasOffset())
4921 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004922 }
4923
scygan2c864272016-05-18 18:09:17 +02004924 if (symbol->getQualifier().hasLocation())
4925 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004926 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004927 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004928 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004929 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004930 }
John Kessenich140f3df2015-06-26 16:58:36 -06004931 if (symbol->getQualifier().hasSet())
4932 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004933 else if (IsDescriptorResource(symbol->getType())) {
4934 // default to 0
4935 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4936 }
John Kessenich140f3df2015-06-26 16:58:36 -06004937 if (symbol->getQualifier().hasBinding())
4938 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004939 if (symbol->getQualifier().hasAttachment())
4940 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004941 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004942 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004943 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004944 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004945 if (symbol->getQualifier().hasXfbBuffer())
4946 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4947 }
4948
Rex Xu1da878f2016-02-21 20:59:01 +08004949 if (symbol->getType().isImage()) {
4950 std::vector<spv::Decoration> memory;
4951 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4952 for (unsigned int i = 0; i < memory.size(); ++i)
4953 addDecoration(id, memory[i]);
4954 }
4955
John Kessenich140f3df2015-06-26 16:58:36 -06004956 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004957 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004958 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004959 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004960
John Kessenichecba76f2017-01-06 00:34:48 -07004961#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004962 if (builtIn == spv::BuiltInSampleMask) {
4963 spv::Decoration decoration;
4964 // GL_NV_sample_mask_override_coverage extension
4965 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004966 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004967 else
4968 decoration = (spv::Decoration)spv::DecorationMax;
4969 addDecoration(id, decoration);
4970 if (decoration != spv::DecorationMax) {
4971 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4972 }
4973 }
chaoc771d89f2017-01-13 01:10:53 -08004974 else if (builtIn == spv::BuiltInLayer) {
4975 // SPV_NV_viewport_array2 extension
4976 if (symbol->getQualifier().layoutViewportRelative)
4977 {
4978 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4979 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4980 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4981 }
4982 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4983 {
4984 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4985 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4986 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4987 }
4988 }
4989
chaoc6e5acae2016-12-20 13:28:52 -08004990 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004991 addDecoration(id, spv::DecorationPassthroughNV);
4992 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004993 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4994 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004995#endif
4996
John Kessenich140f3df2015-06-26 16:58:36 -06004997 return id;
4998}
4999
John Kessenich55e7d112015-11-15 21:33:39 -07005000// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005001void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5002{
John Kessenich4016e382016-07-15 11:53:56 -06005003 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005004 builder.addDecoration(id, dec);
5005}
5006
John Kessenich55e7d112015-11-15 21:33:39 -07005007// If 'dec' is valid, add a one-operand decoration to an object
5008void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5009{
John Kessenich4016e382016-07-15 11:53:56 -06005010 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005011 builder.addDecoration(id, dec, value);
5012}
5013
5014// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005015void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5016{
John Kessenich4016e382016-07-15 11:53:56 -06005017 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005018 builder.addMemberDecoration(id, (unsigned)member, dec);
5019}
5020
John Kessenich92187592016-02-01 13:45:25 -07005021// If 'dec' is valid, add a one-operand decoration to a struct member
5022void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5023{
John Kessenich4016e382016-07-15 11:53:56 -06005024 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005025 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5026}
5027
John Kessenich55e7d112015-11-15 21:33:39 -07005028// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005029// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005030//
5031// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5032//
5033// Recursively walk the nodes. The nodes form a tree whose leaves are
5034// regular constants, which themselves are trees that createSpvConstant()
5035// recursively walks. So, this function walks the "top" of the tree:
5036// - emit specialization constant-building instructions for specConstant
5037// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005038spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005039{
John Kessenich7cc0e282016-03-20 00:46:02 -06005040 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005041
qining4f4bb812016-04-03 23:55:17 -04005042 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005043 if (! node.getQualifier().specConstant) {
5044 // hand off to the non-spec-constant path
5045 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5046 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005047 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005048 nextConst, false);
5049 }
5050
5051 // We now know we have a specialization constant to build
5052
John Kessenichd94c0032016-05-30 19:29:40 -06005053 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005054 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5055 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5056 std::vector<spv::Id> dimConstId;
5057 for (int dim = 0; dim < 3; ++dim) {
5058 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5059 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5060 if (specConst)
5061 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5062 }
5063 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5064 }
5065
5066 // An AST node labelled as specialization constant should be a symbol node.
5067 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5068 if (auto* sn = node.getAsSymbolNode()) {
5069 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005070 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5071 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5072 // will set the builder into spec constant op instruction generating mode.
5073 sub_tree->traverse(this);
5074 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005075 } else if (auto* const_union_array = &sn->getConstArray()){
5076 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005077 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5078 builder.addName(id, sn->getName().c_str());
5079 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005080 }
5081 }
qining4f4bb812016-04-03 23:55:17 -04005082
5083 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5084 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005085 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005086 exit(1);
5087 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005088}
5089
John Kessenich140f3df2015-06-26 16:58:36 -06005090// Use 'consts' as the flattened glslang source of scalar constants to recursively
5091// build the aggregate SPIR-V constant.
5092//
5093// If there are not enough elements present in 'consts', 0 will be substituted;
5094// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5095//
qining08408382016-03-21 09:51:37 -04005096spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005097{
5098 // vector of constants for SPIR-V
5099 std::vector<spv::Id> spvConsts;
5100
5101 // Type is used for struct and array constants
5102 spv::Id typeId = convertGlslangToSpvType(glslangType);
5103
5104 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005105 glslang::TType elementType(glslangType, 0);
5106 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005107 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005108 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005109 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005110 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005111 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005112 } else if (glslangType.getStruct()) {
5113 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5114 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005115 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005116 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005117 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5118 bool zero = nextConst >= consts.size();
5119 switch (glslangType.getBasicType()) {
5120 case glslang::EbtInt:
5121 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5122 break;
5123 case glslang::EbtUint:
5124 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5125 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005126 case glslang::EbtInt64:
5127 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5128 break;
5129 case glslang::EbtUint64:
5130 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5131 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005132 case glslang::EbtFloat:
5133 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5134 break;
5135 case glslang::EbtDouble:
5136 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5137 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005138#ifdef AMD_EXTENSIONS
5139 case glslang::EbtFloat16:
5140 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5141 break;
5142#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005143 case glslang::EbtBool:
5144 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5145 break;
5146 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005147 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005148 break;
5149 }
5150 ++nextConst;
5151 }
5152 } else {
5153 // we have a non-aggregate (scalar) constant
5154 bool zero = nextConst >= consts.size();
5155 spv::Id scalar = 0;
5156 switch (glslangType.getBasicType()) {
5157 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005158 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005159 break;
5160 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005161 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005162 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005163 case glslang::EbtInt64:
5164 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5165 break;
5166 case glslang::EbtUint64:
5167 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5168 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005169 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005170 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005171 break;
5172 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005173 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005174 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005175#ifdef AMD_EXTENSIONS
5176 case glslang::EbtFloat16:
5177 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5178 break;
5179#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005180 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005181 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005184 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005185 break;
5186 }
5187 ++nextConst;
5188 return scalar;
5189 }
5190
5191 return builder.makeCompositeConstant(typeId, spvConsts);
5192}
5193
John Kessenich7c1aa102015-10-15 13:29:11 -06005194// Return true if the node is a constant or symbol whose reading has no
5195// non-trivial observable cost or effect.
5196bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5197{
5198 // don't know what this is
5199 if (node == nullptr)
5200 return false;
5201
5202 // a constant is safe
5203 if (node->getAsConstantUnion() != nullptr)
5204 return true;
5205
5206 // not a symbol means non-trivial
5207 if (node->getAsSymbolNode() == nullptr)
5208 return false;
5209
5210 // a symbol, depends on what's being read
5211 switch (node->getType().getQualifier().storage) {
5212 case glslang::EvqTemporary:
5213 case glslang::EvqGlobal:
5214 case glslang::EvqIn:
5215 case glslang::EvqInOut:
5216 case glslang::EvqConst:
5217 case glslang::EvqConstReadOnly:
5218 case glslang::EvqUniform:
5219 return true;
5220 default:
5221 return false;
5222 }
qining25262b32016-05-06 17:25:16 -04005223}
John Kessenich7c1aa102015-10-15 13:29:11 -06005224
5225// A node is trivial if it is a single operation with no side effects.
5226// Error on the side of saying non-trivial.
5227// Return true if trivial.
5228bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5229{
5230 if (node == nullptr)
5231 return false;
5232
5233 // symbols and constants are trivial
5234 if (isTrivialLeaf(node))
5235 return true;
5236
5237 // otherwise, it needs to be a simple operation or one or two leaf nodes
5238
5239 // not a simple operation
5240 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5241 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5242 if (binaryNode == nullptr && unaryNode == nullptr)
5243 return false;
5244
5245 // not on leaf nodes
5246 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5247 return false;
5248
5249 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5250 return false;
5251 }
5252
5253 switch (node->getAsOperator()->getOp()) {
5254 case glslang::EOpLogicalNot:
5255 case glslang::EOpConvIntToBool:
5256 case glslang::EOpConvUintToBool:
5257 case glslang::EOpConvFloatToBool:
5258 case glslang::EOpConvDoubleToBool:
5259 case glslang::EOpEqual:
5260 case glslang::EOpNotEqual:
5261 case glslang::EOpLessThan:
5262 case glslang::EOpGreaterThan:
5263 case glslang::EOpLessThanEqual:
5264 case glslang::EOpGreaterThanEqual:
5265 case glslang::EOpIndexDirect:
5266 case glslang::EOpIndexDirectStruct:
5267 case glslang::EOpLogicalXor:
5268 case glslang::EOpAny:
5269 case glslang::EOpAll:
5270 return true;
5271 default:
5272 return false;
5273 }
5274}
5275
5276// Emit short-circuiting code, where 'right' is never evaluated unless
5277// the left side is true (for &&) or false (for ||).
5278spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5279{
5280 spv::Id boolTypeId = builder.makeBoolType();
5281
5282 // emit left operand
5283 builder.clearAccessChain();
5284 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005285 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005286
5287 // Operands to accumulate OpPhi operands
5288 std::vector<spv::Id> phiOperands;
5289 // accumulate left operand's phi information
5290 phiOperands.push_back(leftId);
5291 phiOperands.push_back(builder.getBuildPoint()->getId());
5292
5293 // Make the two kinds of operation symmetric with a "!"
5294 // || => emit "if (! left) result = right"
5295 // && => emit "if ( left) result = right"
5296 //
5297 // TODO: this runtime "not" for || could be avoided by adding functionality
5298 // to 'builder' to have an "else" without an "then"
5299 if (op == glslang::EOpLogicalOr)
5300 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5301
5302 // make an "if" based on the left value
5303 spv::Builder::If ifBuilder(leftId, builder);
5304
5305 // emit right operand as the "then" part of the "if"
5306 builder.clearAccessChain();
5307 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005308 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005309
5310 // accumulate left operand's phi information
5311 phiOperands.push_back(rightId);
5312 phiOperands.push_back(builder.getBuildPoint()->getId());
5313
5314 // finish the "if"
5315 ifBuilder.makeEndIf();
5316
5317 // phi together the two results
5318 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5319}
5320
Rex Xu9d93a232016-05-05 12:30:44 +08005321// Return type Id of the imported set of extended instructions corresponds to the name.
5322// Import this set if it has not been imported yet.
5323spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5324{
5325 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5326 return extBuiltinMap[name];
5327 else {
Rex Xu51596642016-09-21 18:56:12 +08005328 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005329 spv::Id extBuiltins = builder.import(name);
5330 extBuiltinMap[name] = extBuiltins;
5331 return extBuiltins;
5332 }
5333}
5334
John Kessenich140f3df2015-06-26 16:58:36 -06005335}; // end anonymous namespace
5336
5337namespace glslang {
5338
John Kessenich68d78fd2015-07-12 19:28:10 -06005339void GetSpirvVersion(std::string& version)
5340{
John Kessenich9e55f632015-07-15 10:03:39 -06005341 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005342 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005343 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005344 version = buf;
5345}
5346
John Kessenich140f3df2015-06-26 16:58:36 -06005347// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005348void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005349{
5350 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005351 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005352 if (out.fail())
5353 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005354 for (int i = 0; i < (int)spirv.size(); ++i) {
5355 unsigned int word = spirv[i];
5356 out.write((const char*)&word, 4);
5357 }
5358 out.close();
5359}
5360
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005361// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005362void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005363{
5364 std::ofstream out;
5365 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005366 if (out.fail())
5367 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005368 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005369 if (varName != nullptr) {
5370 out << "\t #pragma once" << std::endl;
5371 out << "const uint32_t " << varName << "[] = {" << std::endl;
5372 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005373 const int WORDS_PER_LINE = 8;
5374 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5375 out << "\t";
5376 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5377 const unsigned int word = spirv[i + j];
5378 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5379 if (i + j + 1 < (int)spirv.size()) {
5380 out << ",";
5381 }
5382 }
5383 out << std::endl;
5384 }
Flavio15017db2017-02-15 14:29:33 -08005385 if (varName != nullptr) {
5386 out << "};";
5387 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005388 out.close();
5389}
5390
John Kessenich140f3df2015-06-26 16:58:36 -06005391//
5392// Set up the glslang traversal
5393//
5394void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5395{
Lei Zhang17535f72016-05-04 15:55:59 -04005396 spv::SpvBuildLogger logger;
5397 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005398}
5399
Lei Zhang17535f72016-05-04 15:55:59 -04005400void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005401{
John Kessenich140f3df2015-06-26 16:58:36 -06005402 TIntermNode* root = intermediate.getTreeRoot();
5403
5404 if (root == 0)
5405 return;
5406
5407 glslang::GetThreadPoolAllocator().push();
5408
Lei Zhang17535f72016-05-04 15:55:59 -04005409 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005410 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005411 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005412 it.dumpSpv(spirv);
5413
5414 glslang::GetThreadPoolAllocator().pop();
5415}
5416
5417}; // end namespace glslang