blob: 5385eeefbc8fc70bf0d7395c01ce7174d09bc7fd [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:
qining3d7b89a2016-03-07 21:32:15 -0500483 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800484#ifdef NV_EXTENSIONS
485 if (glslangIntermediate->getStage() == EShLangVertex ||
486 glslangIntermediate->getStage() == EShLangTessControl ||
487 glslangIntermediate->getStage() == EShLangTessEvaluation)
488 {
489 builder.addExtension(spv::E_SPV_NV_viewport_array2);
490 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
491 }
492#endif
John Kessenich92187592016-02-01 13:45:25 -0700493 return spv::BuiltInViewportIndex;
494
John Kessenich5e801132016-02-15 11:09:46 -0700495 case glslang::EbvSampleId:
496 builder.addCapability(spv::CapabilitySampleRateShading);
497 return spv::BuiltInSampleId;
498
499 case glslang::EbvSamplePosition:
500 builder.addCapability(spv::CapabilitySampleRateShading);
501 return spv::BuiltInSamplePosition;
502
503 case glslang::EbvSampleMask:
504 builder.addCapability(spv::CapabilitySampleRateShading);
505 return spv::BuiltInSampleMask;
506
John Kessenich78a45572016-07-08 14:05:15 -0600507 case glslang::EbvLayer:
508 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800509#ifdef NV_EXTENSIONS
510 if (!memberDeclaration)
511 {
512 if (glslangIntermediate->getStage() == EShLangVertex ||
513 glslangIntermediate->getStage() == EShLangTessControl ||
514 glslangIntermediate->getStage() == EShLangTessEvaluation)
515 {
516 builder.addExtension(spv::E_SPV_NV_viewport_array2);
517 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
518 }
519 }
520#endif
John Kessenich78a45572016-07-08 14:05:15 -0600521 return spv::BuiltInLayer;
522
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvVertexId: return spv::BuiltInVertexId;
525 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700526 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
527 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800528
John Kessenichda581a22015-10-14 14:10:30 -0600529 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800530 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
531 builder.addCapability(spv::CapabilityDrawParameters);
532 return spv::BuiltInBaseVertex;
533
John Kessenichda581a22015-10-14 14:10:30 -0600534 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
536 builder.addCapability(spv::CapabilityDrawParameters);
537 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200538
John Kessenichda581a22015-10-14 14:10:30 -0600539 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
541 builder.addCapability(spv::CapabilityDrawParameters);
542 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200543
544 case glslang::EbvPrimitiveId:
545 if (glslangIntermediate->getStage() == EShLangFragment)
546 builder.addCapability(spv::CapabilityGeometry);
547 return spv::BuiltInPrimitiveId;
548
John Kessenich140f3df2015-06-26 16:58:36 -0600549 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600550 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
551 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
552 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
553 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
554 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
555 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
556 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600557 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
558 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
559 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
560 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
561 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
562 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
563 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
564 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupSize;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLocalInvocationId;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupEqMaskKHR;
580
Rex Xu574ab042016-04-14 16:53:07 +0800581 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800582 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
583 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
584 return spv::BuiltInSubgroupGeMaskKHR;
585
Rex Xu574ab042016-04-14 16:53:07 +0800586 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800587 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
588 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
589 return spv::BuiltInSubgroupGtMaskKHR;
590
Rex Xu574ab042016-04-14 16:53:07 +0800591 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800592 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
593 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
594 return spv::BuiltInSubgroupLeMaskKHR;
595
Rex Xu574ab042016-04-14 16:53:07 +0800596 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800597 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
598 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
599 return spv::BuiltInSubgroupLtMaskKHR;
600
Rex Xu9d93a232016-05-05 12:30:44 +0800601#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800602 case glslang::EbvBaryCoordNoPersp:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordNoPerspAMD;
605
606 case glslang::EbvBaryCoordNoPerspCentroid:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
609
610 case glslang::EbvBaryCoordNoPerspSample:
611 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
612 return spv::BuiltInBaryCoordNoPerspSampleAMD;
613
614 case glslang::EbvBaryCoordSmooth:
615 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
616 return spv::BuiltInBaryCoordSmoothAMD;
617
618 case glslang::EbvBaryCoordSmoothCentroid:
619 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
620 return spv::BuiltInBaryCoordSmoothCentroidAMD;
621
622 case glslang::EbvBaryCoordSmoothSample:
623 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
624 return spv::BuiltInBaryCoordSmoothSampleAMD;
625
626 case glslang::EbvBaryCoordPullModel:
627 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
628 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800629#endif
chaoc771d89f2017-01-13 01:10:53 -0800630
John Kessenich6c8aaac2017-02-27 01:20:51 -0700631 case glslang::EbvDeviceIndex:
632 builder.addExtension(spv::E_SPV_KHR_device_group);
633 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700634 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700635
636 case glslang::EbvViewIndex:
637 builder.addExtension(spv::E_SPV_KHR_multiview);
638 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700639 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700640
chaoc771d89f2017-01-13 01:10:53 -0800641#ifdef NV_EXTENSIONS
642 case glslang::EbvViewportMaskNV:
643 builder.addExtension(spv::E_SPV_NV_viewport_array2);
644 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
645 return spv::BuiltInViewportMaskNV;
646 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800647 if (!memberDeclaration) {
648 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
649 builder.addCapability(spv::CapabilityShaderStereoViewNV);
650 }
chaoc771d89f2017-01-13 01:10:53 -0800651 return spv::BuiltInSecondaryPositionNV;
652 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800653 if (!memberDeclaration) {
654 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
655 builder.addCapability(spv::CapabilityShaderStereoViewNV);
656 }
chaoc771d89f2017-01-13 01:10:53 -0800657 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800658 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800659 if (!memberDeclaration) {
660 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
661 builder.addCapability(spv::CapabilityPerViewAttributesNV);
662 }
chaocdf3956c2017-02-14 14:52:34 -0800663 return spv::BuiltInPositionPerViewNV;
664 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800665 if (!memberDeclaration) {
666 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
667 builder.addCapability(spv::CapabilityPerViewAttributesNV);
668 }
chaocdf3956c2017-02-14 14:52:34 -0800669 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800670#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800671 default:
672 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600673 }
674}
675
Rex Xufc618912015-09-09 16:42:49 +0800676// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700677spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800678{
679 assert(type.getBasicType() == glslang::EbtSampler);
680
John Kessenich5d0fa972016-02-15 11:57:00 -0700681 // Check for capabilities
682 switch (type.getQualifier().layoutFormat) {
683 case glslang::ElfRg32f:
684 case glslang::ElfRg16f:
685 case glslang::ElfR11fG11fB10f:
686 case glslang::ElfR16f:
687 case glslang::ElfRgba16:
688 case glslang::ElfRgb10A2:
689 case glslang::ElfRg16:
690 case glslang::ElfRg8:
691 case glslang::ElfR16:
692 case glslang::ElfR8:
693 case glslang::ElfRgba16Snorm:
694 case glslang::ElfRg16Snorm:
695 case glslang::ElfRg8Snorm:
696 case glslang::ElfR16Snorm:
697 case glslang::ElfR8Snorm:
698
699 case glslang::ElfRg32i:
700 case glslang::ElfRg16i:
701 case glslang::ElfRg8i:
702 case glslang::ElfR16i:
703 case glslang::ElfR8i:
704
705 case glslang::ElfRgb10a2ui:
706 case glslang::ElfRg32ui:
707 case glslang::ElfRg16ui:
708 case glslang::ElfRg8ui:
709 case glslang::ElfR16ui:
710 case glslang::ElfR8ui:
711 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
712 break;
713
714 default:
715 break;
716 }
717
718 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800719 switch (type.getQualifier().layoutFormat) {
720 case glslang::ElfNone: return spv::ImageFormatUnknown;
721 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
722 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
723 case glslang::ElfR32f: return spv::ImageFormatR32f;
724 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
725 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
726 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
727 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
728 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
729 case glslang::ElfR16f: return spv::ImageFormatR16f;
730 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
731 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
732 case glslang::ElfRg16: return spv::ImageFormatRg16;
733 case glslang::ElfRg8: return spv::ImageFormatRg8;
734 case glslang::ElfR16: return spv::ImageFormatR16;
735 case glslang::ElfR8: return spv::ImageFormatR8;
736 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
737 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
738 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
739 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
740 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
741 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
742 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
743 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
744 case glslang::ElfR32i: return spv::ImageFormatR32i;
745 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
746 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
747 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
748 case glslang::ElfR16i: return spv::ImageFormatR16i;
749 case glslang::ElfR8i: return spv::ImageFormatR8i;
750 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
751 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
752 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
753 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
754 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
755 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
756 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
757 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
758 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
759 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600760 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800761 }
762}
763
qining25262b32016-05-06 17:25:16 -0400764// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700765// descriptor set.
766bool IsDescriptorResource(const glslang::TType& type)
767{
John Kessenichf7497e22016-03-08 21:36:22 -0700768 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700769 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700770 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700771
772 // non block...
773 // basically samplerXXX/subpass/sampler/texture are all included
774 // if they are the global-scope-class, not the function parameter
775 // (or local, if they ever exist) class.
776 if (type.getBasicType() == glslang::EbtSampler)
777 return type.getQualifier().isUniformOrBuffer();
778
779 // None of the above.
780 return false;
781}
782
John Kesseniche0b6cad2015-12-24 10:30:13 -0700783void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
784{
785 if (child.layoutMatrix == glslang::ElmNone)
786 child.layoutMatrix = parent.layoutMatrix;
787
788 if (parent.invariant)
789 child.invariant = true;
790 if (parent.nopersp)
791 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800792#ifdef AMD_EXTENSIONS
793 if (parent.explicitInterp)
794 child.explicitInterp = true;
795#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700796 if (parent.flat)
797 child.flat = true;
798 if (parent.centroid)
799 child.centroid = true;
800 if (parent.patch)
801 child.patch = true;
802 if (parent.sample)
803 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800804 if (parent.coherent)
805 child.coherent = true;
806 if (parent.volatil)
807 child.volatil = true;
808 if (parent.restrict)
809 child.restrict = true;
810 if (parent.readonly)
811 child.readonly = true;
812 if (parent.writeonly)
813 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700814}
815
John Kessenichf2b7f332016-09-01 17:05:23 -0600816bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817{
John Kessenich7b9fa252016-01-21 18:56:57 -0700818 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600819 // - struct members might inherit from a struct declaration
820 // (note that non-block structs don't explicitly inherit,
821 // only implicitly, meaning no decoration involved)
822 // - affect decorations on the struct members
823 // (note smooth does not, and expecting something like volatile
824 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700825 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600826 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700827}
828
John Kessenich140f3df2015-06-26 16:58:36 -0600829//
830// Implement the TGlslangToSpvTraverser class.
831//
832
Lei Zhang17535f72016-05-04 15:55:59 -0400833TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600834 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
835 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400836 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700837 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600838 glslangIntermediate(glslangIntermediate)
839{
840 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
841
842 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700843 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600844 stdBuiltins = builder.import("GLSL.std.450");
845 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600846 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
847 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600848
849 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600850 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
851 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600852 builder.addSourceExtension(it->c_str());
853
854 // Add the top-level modes for this shader.
855
John Kessenich92187592016-02-01 13:45:25 -0700856 if (glslangIntermediate->getXfbMode()) {
857 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600858 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700859 }
John Kessenich140f3df2015-06-26 16:58:36 -0600860
861 unsigned int mode;
862 switch (glslangIntermediate->getStage()) {
863 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600864 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600865 break;
866
867 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
870 break;
871
872 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700875 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
876 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
877 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600878 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600879 }
John Kessenich4016e382016-07-15 11:53:56 -0600880 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600881 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
882
John Kesseniche6903322015-10-13 16:29:02 -0600883 switch (glslangIntermediate->getVertexSpacing()) {
884 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
885 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
886 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600887 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600888 }
John Kessenich4016e382016-07-15 11:53:56 -0600889 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600890 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
891
892 switch (glslangIntermediate->getVertexOrder()) {
893 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
894 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600895 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600896 }
John Kessenich4016e382016-07-15 11:53:56 -0600897 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600898 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
899
900 if (glslangIntermediate->getPointMode())
901 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600902 break;
903
904 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600905 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600906 switch (glslangIntermediate->getInputPrimitive()) {
907 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
908 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
909 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700910 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600911 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600912 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600913 }
John Kessenich4016e382016-07-15 11:53:56 -0600914 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600915 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600916
John Kessenich140f3df2015-06-26 16:58:36 -0600917 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
918
919 switch (glslangIntermediate->getOutputPrimitive()) {
920 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
921 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
922 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600923 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600924 }
John Kessenich4016e382016-07-15 11:53:56 -0600925 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600926 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
927 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
928 break;
929
930 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600931 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600932 if (glslangIntermediate->getPixelCenterInteger())
933 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600934
John Kessenich140f3df2015-06-26 16:58:36 -0600935 if (glslangIntermediate->getOriginUpperLeft())
936 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600937 else
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600939
940 if (glslangIntermediate->getEarlyFragmentTests())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
942
943 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600944 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
945 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600946 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600947 }
John Kessenich4016e382016-07-15 11:53:56 -0600948 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600949 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
950
951 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 break;
954
955 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
958 glslangIntermediate->getLocalSize(1),
959 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600960 break;
961
962 default:
963 break;
964 }
John Kessenich140f3df2015-06-26 16:58:36 -0600965}
966
John Kessenichfca82622016-11-26 13:23:20 -0700967// Finish creating SPV, after the traversal is complete.
968void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700969{
John Kessenich517fe7a2016-11-26 13:31:47 -0700970 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700971 builder.setBuildPoint(shaderEntry->getLastBlock());
972 builder.leaveFunction();
973 }
974
John Kessenich7ba63412015-12-20 17:37:07 -0700975 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100976 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
977 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700978
qiningda397332016-03-09 19:54:03 -0500979 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700980}
981
John Kessenichfca82622016-11-26 13:23:20 -0700982// Write the SPV into 'out'.
983void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600984{
John Kessenichfca82622016-11-26 13:23:20 -0700985 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600986}
987
988//
989// Implement the traversal functions.
990//
991// Return true from interior nodes to have the external traversal
992// continue on to children. Return false if children were
993// already processed.
994//
995
996//
qining25262b32016-05-06 17:25:16 -0400997// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600998// - uniform/input reads
999// - output writes
1000// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1001// - something simple that degenerates into the last bullet
1002//
1003void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1004{
qining75d1d802016-04-06 14:42:01 -04001005 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1006 if (symbol->getType().getQualifier().isSpecConstant())
1007 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1008
John Kessenich140f3df2015-06-26 16:58:36 -06001009 // getSymbolId() will set up all the IO decorations on the first call.
1010 // Formal function parameters were mapped during makeFunctions().
1011 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001012
1013 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1014 if (builder.isPointer(id)) {
1015 spv::StorageClass sc = builder.getStorageClass(id);
1016 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1017 iOSet.insert(id);
1018 }
1019
1020 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001021 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001022 // Prepare to generate code for the access
1023
1024 // L-value chains will be computed left to right. We're on the symbol now,
1025 // which is the left-most part of the access chain, so now is "clear" time,
1026 // followed by setting the base.
1027 builder.clearAccessChain();
1028
1029 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001030 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001031 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001032 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001033 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001034 // These are also pure R-values.
1035 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001036 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001037 builder.setAccessChainRValue(id);
1038 else
1039 builder.setAccessChainLValue(id);
1040 }
1041}
1042
1043bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1044{
qining40887662016-04-03 22:20:42 -04001045 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1046 if (node->getType().getQualifier().isSpecConstant())
1047 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1048
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // First, handle special cases
1050 switch (node->getOp()) {
1051 case glslang::EOpAssign:
1052 case glslang::EOpAddAssign:
1053 case glslang::EOpSubAssign:
1054 case glslang::EOpMulAssign:
1055 case glslang::EOpVectorTimesMatrixAssign:
1056 case glslang::EOpVectorTimesScalarAssign:
1057 case glslang::EOpMatrixTimesScalarAssign:
1058 case glslang::EOpMatrixTimesMatrixAssign:
1059 case glslang::EOpDivAssign:
1060 case glslang::EOpModAssign:
1061 case glslang::EOpAndAssign:
1062 case glslang::EOpInclusiveOrAssign:
1063 case glslang::EOpExclusiveOrAssign:
1064 case glslang::EOpLeftShiftAssign:
1065 case glslang::EOpRightShiftAssign:
1066 // A bin-op assign "a += b" means the same thing as "a = a + b"
1067 // where a is evaluated before b. For a simple assignment, GLSL
1068 // says to evaluate the left before the right. So, always, left
1069 // node then right node.
1070 {
1071 // get the left l-value, save it away
1072 builder.clearAccessChain();
1073 node->getLeft()->traverse(this);
1074 spv::Builder::AccessChain lValue = builder.getAccessChain();
1075
1076 // evaluate the right
1077 builder.clearAccessChain();
1078 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001079 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001080
1081 if (node->getOp() != glslang::EOpAssign) {
1082 // the left is also an r-value
1083 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001084 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001085
1086 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001087 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001088 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001089 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1090 node->getType().getBasicType());
1091
1092 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001093 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001094 }
1095
1096 // store the result
1097 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001098 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001099
1100 // assignments are expressions having an rValue after they are evaluated...
1101 builder.clearAccessChain();
1102 builder.setAccessChainRValue(rValue);
1103 }
1104 return false;
1105 case glslang::EOpIndexDirect:
1106 case glslang::EOpIndexDirectStruct:
1107 {
1108 // Get the left part of the access chain.
1109 node->getLeft()->traverse(this);
1110
1111 // Add the next element in the chain
1112
David Netoa901ffe2016-06-08 14:11:40 +01001113 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001114 if (! node->getLeft()->getType().isArray() &&
1115 node->getLeft()->getType().isVector() &&
1116 node->getOp() == glslang::EOpIndexDirect) {
1117 // This is essentially a hard-coded vector swizzle of size 1,
1118 // so short circuit the access-chain stuff with a swizzle.
1119 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001120 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001121 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001122 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001123 int spvIndex = glslangIndex;
1124 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1125 node->getOp() == glslang::EOpIndexDirectStruct)
1126 {
1127 // This may be, e.g., an anonymous block-member selection, which generally need
1128 // index remapping due to hidden members in anonymous blocks.
1129 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1130 assert(remapper.size() > 0);
1131 spvIndex = remapper[glslangIndex];
1132 }
John Kessenichebb50532016-05-16 19:22:05 -06001133
David Netoa901ffe2016-06-08 14:11:40 +01001134 // normal case for indexing array or structure or block
1135 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1136
1137 // Add capabilities here for accessing PointSize and clip/cull distance.
1138 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001139 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001140 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001141 }
1142 }
1143 return false;
1144 case glslang::EOpIndexIndirect:
1145 {
1146 // Structure or array or vector indirection.
1147 // Will use native SPIR-V access-chain for struct and array indirection;
1148 // matrices are arrays of vectors, so will also work for a matrix.
1149 // Will use the access chain's 'component' for variable index into a vector.
1150
1151 // This adapter is building access chains left to right.
1152 // Set up the access chain to the left.
1153 node->getLeft()->traverse(this);
1154
1155 // save it so that computing the right side doesn't trash it
1156 spv::Builder::AccessChain partial = builder.getAccessChain();
1157
1158 // compute the next index in the chain
1159 builder.clearAccessChain();
1160 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001161 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001162
1163 // restore the saved access chain
1164 builder.setAccessChain(partial);
1165
1166 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001167 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001168 else
John Kessenichfa668da2015-09-13 14:46:30 -06001169 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001170 }
1171 return false;
1172 case glslang::EOpVectorSwizzle:
1173 {
1174 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001175 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001176 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001177 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001178 }
1179 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001180 case glslang::EOpMatrixSwizzle:
1181 logger->missingFunctionality("matrix swizzle");
1182 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001183 case glslang::EOpLogicalOr:
1184 case glslang::EOpLogicalAnd:
1185 {
1186
1187 // These may require short circuiting, but can sometimes be done as straight
1188 // binary operations. The right operand must be short circuited if it has
1189 // side effects, and should probably be if it is complex.
1190 if (isTrivial(node->getRight()->getAsTyped()))
1191 break; // handle below as a normal binary operation
1192 // otherwise, we need to do dynamic short circuiting on the right operand
1193 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1194 builder.clearAccessChain();
1195 builder.setAccessChainRValue(result);
1196 }
1197 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001198 default:
1199 break;
1200 }
1201
1202 // Assume generic binary op...
1203
John Kessenich32cfd492016-02-02 12:37:46 -07001204 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001205 builder.clearAccessChain();
1206 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001207 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001208
John Kessenich32cfd492016-02-02 12:37:46 -07001209 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.clearAccessChain();
1211 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001212 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001215 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001216 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001217 convertGlslangToSpvType(node->getType()), left, right,
1218 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001219
John Kessenich50e57562015-12-21 21:21:11 -07001220 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001221 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001222 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001223 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001224 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001225 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001226 return false;
1227 }
John Kessenich140f3df2015-06-26 16:58:36 -06001228}
1229
1230bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1231{
qining40887662016-04-03 22:20:42 -04001232 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1233 if (node->getType().getQualifier().isSpecConstant())
1234 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1235
John Kessenichfc51d282015-08-19 13:34:18 -06001236 spv::Id result = spv::NoResult;
1237
1238 // try texturing first
1239 result = createImageTextureFunctionCall(node);
1240 if (result != spv::NoResult) {
1241 builder.clearAccessChain();
1242 builder.setAccessChainRValue(result);
1243
1244 return false; // done with this node
1245 }
1246
1247 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001248
1249 if (node->getOp() == glslang::EOpArrayLength) {
1250 // Quite special; won't want to evaluate the operand.
1251
1252 // Normal .length() would have been constant folded by the front-end.
1253 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001254 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001255 assert(node->getOperand()->getType().isRuntimeSizedArray());
1256 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1257 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001258 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1259 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001260
1261 builder.clearAccessChain();
1262 builder.setAccessChainRValue(length);
1263
1264 return false;
1265 }
1266
John Kessenichfc51d282015-08-19 13:34:18 -06001267 // Start by evaluating the operand
1268
John Kessenich8c8505c2016-07-26 12:50:38 -06001269 // Does it need a swizzle inversion? If so, evaluation is inverted;
1270 // operate first on the swizzle base, then apply the swizzle.
1271 spv::Id invertedType = spv::NoType;
1272 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1273 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1274 invertedType = getInvertedSwizzleType(*node->getOperand());
1275
John Kessenich140f3df2015-06-26 16:58:36 -06001276 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001277 if (invertedType != spv::NoType)
1278 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1279 else
1280 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001281
Rex Xufc618912015-09-09 16:42:49 +08001282 spv::Id operand = spv::NoResult;
1283
1284 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1285 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001286 node->getOp() == glslang::EOpAtomicCounter ||
1287 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001288 operand = builder.accessChainGetLValue(); // Special case l-value operands
1289 else
John Kessenich32cfd492016-02-02 12:37:46 -07001290 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001291
John Kessenichf6640762016-08-01 19:44:00 -06001292 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001293 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001294
1295 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001296 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001297 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 // if not, then possibly an operation
1300 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001301 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType)
1305 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1306
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.clearAccessChain();
1308 builder.setAccessChainRValue(result);
1309
1310 return false; // done with this node
1311 }
1312
1313 // it must be a special case, check...
1314 switch (node->getOp()) {
1315 case glslang::EOpPostIncrement:
1316 case glslang::EOpPostDecrement:
1317 case glslang::EOpPreIncrement:
1318 case glslang::EOpPreDecrement:
1319 {
1320 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001321 spv::Id one = 0;
1322 if (node->getBasicType() == glslang::EbtFloat)
1323 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001324 else if (node->getBasicType() == glslang::EbtDouble)
1325 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001326#ifdef AMD_EXTENSIONS
1327 else if (node->getBasicType() == glslang::EbtFloat16)
1328 one = builder.makeFloat16Constant(1.0F);
1329#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001330 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1331 one = builder.makeInt64Constant(1);
1332 else
1333 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001334 glslang::TOperator op;
1335 if (node->getOp() == glslang::EOpPreIncrement ||
1336 node->getOp() == glslang::EOpPostIncrement)
1337 op = glslang::EOpAdd;
1338 else
1339 op = glslang::EOpSub;
1340
John Kessenichf6640762016-08-01 19:44:00 -06001341 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001342 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001343 convertGlslangToSpvType(node->getType()), operand, one,
1344 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001345 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001346
1347 // The result of operation is always stored, but conditionally the
1348 // consumed result. The consumed result is always an r-value.
1349 builder.accessChainStore(result);
1350 builder.clearAccessChain();
1351 if (node->getOp() == glslang::EOpPreIncrement ||
1352 node->getOp() == glslang::EOpPreDecrement)
1353 builder.setAccessChainRValue(result);
1354 else
1355 builder.setAccessChainRValue(operand);
1356 }
1357
1358 return false;
1359
1360 case glslang::EOpEmitStreamVertex:
1361 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1362 return false;
1363 case glslang::EOpEndStreamPrimitive:
1364 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1365 return false;
1366
1367 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001368 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001369 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001370 }
John Kessenich140f3df2015-06-26 16:58:36 -06001371}
1372
1373bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1374{
qining27e04a02016-04-14 16:40:20 -04001375 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1376 if (node->getType().getQualifier().isSpecConstant())
1377 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1378
John Kessenichfc51d282015-08-19 13:34:18 -06001379 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001380 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1381 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001382
1383 // try texturing
1384 result = createImageTextureFunctionCall(node);
1385 if (result != spv::NoResult) {
1386 builder.clearAccessChain();
1387 builder.setAccessChainRValue(result);
1388
1389 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001390 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001391 // "imageStore" is a special case, which has no result
1392 return false;
1393 }
John Kessenichfc51d282015-08-19 13:34:18 -06001394
John Kessenich140f3df2015-06-26 16:58:36 -06001395 glslang::TOperator binOp = glslang::EOpNull;
1396 bool reduceComparison = true;
1397 bool isMatrix = false;
1398 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001399 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001400
1401 assert(node->getOp());
1402
John Kessenichf6640762016-08-01 19:44:00 -06001403 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
1405 switch (node->getOp()) {
1406 case glslang::EOpSequence:
1407 {
1408 if (preVisit)
1409 ++sequenceDepth;
1410 else
1411 --sequenceDepth;
1412
1413 if (sequenceDepth == 1) {
1414 // If this is the parent node of all the functions, we want to see them
1415 // early, so all call points have actual SPIR-V functions to reference.
1416 // In all cases, still let the traverser visit the children for us.
1417 makeFunctions(node->getAsAggregate()->getSequence());
1418
John Kessenich6fccb3c2016-09-19 16:01:41 -06001419 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001420 // anything else gets there, so visit out of order, doing them all now.
1421 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1422
John Kessenich6a60c2f2016-12-08 21:01:59 -07001423 // 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 -06001424 // so do them manually.
1425 visitFunctions(node->getAsAggregate()->getSequence());
1426
1427 return false;
1428 }
1429
1430 return true;
1431 }
1432 case glslang::EOpLinkerObjects:
1433 {
1434 if (visit == glslang::EvPreVisit)
1435 linkageOnly = true;
1436 else
1437 linkageOnly = false;
1438
1439 return true;
1440 }
1441 case glslang::EOpComma:
1442 {
1443 // processing from left to right naturally leaves the right-most
1444 // lying around in the access chain
1445 glslang::TIntermSequence& glslangOperands = node->getSequence();
1446 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1447 glslangOperands[i]->traverse(this);
1448
1449 return false;
1450 }
1451 case glslang::EOpFunction:
1452 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001453 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001454 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001456 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001457 } else {
1458 handleFunctionEntry(node);
1459 }
1460 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001461 if (inEntryPoint)
1462 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001463 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001464 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 }
1466
1467 return true;
1468 case glslang::EOpParameters:
1469 // Parameters will have been consumed by EOpFunction processing, but not
1470 // the body, so we still visited the function node's children, making this
1471 // child redundant.
1472 return false;
1473 case glslang::EOpFunctionCall:
1474 {
1475 if (node->isUserDefined())
1476 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001477 // 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 -07001478 if (result) {
1479 builder.clearAccessChain();
1480 builder.setAccessChainRValue(result);
1481 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001482 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001483
1484 return false;
1485 }
1486 case glslang::EOpConstructMat2x2:
1487 case glslang::EOpConstructMat2x3:
1488 case glslang::EOpConstructMat2x4:
1489 case glslang::EOpConstructMat3x2:
1490 case glslang::EOpConstructMat3x3:
1491 case glslang::EOpConstructMat3x4:
1492 case glslang::EOpConstructMat4x2:
1493 case glslang::EOpConstructMat4x3:
1494 case glslang::EOpConstructMat4x4:
1495 case glslang::EOpConstructDMat2x2:
1496 case glslang::EOpConstructDMat2x3:
1497 case glslang::EOpConstructDMat2x4:
1498 case glslang::EOpConstructDMat3x2:
1499 case glslang::EOpConstructDMat3x3:
1500 case glslang::EOpConstructDMat3x4:
1501 case glslang::EOpConstructDMat4x2:
1502 case glslang::EOpConstructDMat4x3:
1503 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001504#ifdef AMD_EXTENSIONS
1505 case glslang::EOpConstructF16Mat2x2:
1506 case glslang::EOpConstructF16Mat2x3:
1507 case glslang::EOpConstructF16Mat2x4:
1508 case glslang::EOpConstructF16Mat3x2:
1509 case glslang::EOpConstructF16Mat3x3:
1510 case glslang::EOpConstructF16Mat3x4:
1511 case glslang::EOpConstructF16Mat4x2:
1512 case glslang::EOpConstructF16Mat4x3:
1513 case glslang::EOpConstructF16Mat4x4:
1514#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001515 isMatrix = true;
1516 // fall through
1517 case glslang::EOpConstructFloat:
1518 case glslang::EOpConstructVec2:
1519 case glslang::EOpConstructVec3:
1520 case glslang::EOpConstructVec4:
1521 case glslang::EOpConstructDouble:
1522 case glslang::EOpConstructDVec2:
1523 case glslang::EOpConstructDVec3:
1524 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001525#ifdef AMD_EXTENSIONS
1526 case glslang::EOpConstructFloat16:
1527 case glslang::EOpConstructF16Vec2:
1528 case glslang::EOpConstructF16Vec3:
1529 case glslang::EOpConstructF16Vec4:
1530#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EOpConstructBool:
1532 case glslang::EOpConstructBVec2:
1533 case glslang::EOpConstructBVec3:
1534 case glslang::EOpConstructBVec4:
1535 case glslang::EOpConstructInt:
1536 case glslang::EOpConstructIVec2:
1537 case glslang::EOpConstructIVec3:
1538 case glslang::EOpConstructIVec4:
1539 case glslang::EOpConstructUint:
1540 case glslang::EOpConstructUVec2:
1541 case glslang::EOpConstructUVec3:
1542 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001543 case glslang::EOpConstructInt64:
1544 case glslang::EOpConstructI64Vec2:
1545 case glslang::EOpConstructI64Vec3:
1546 case glslang::EOpConstructI64Vec4:
1547 case glslang::EOpConstructUint64:
1548 case glslang::EOpConstructU64Vec2:
1549 case glslang::EOpConstructU64Vec3:
1550 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001551 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001552 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001553 {
1554 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001555 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001556 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001557 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001558 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001559 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001560 std::vector<spv::Id> constituents;
1561 for (int c = 0; c < (int)arguments.size(); ++c)
1562 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001563 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001564 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001565 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001566 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001567 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001568
1569 builder.clearAccessChain();
1570 builder.setAccessChainRValue(constructed);
1571
1572 return false;
1573 }
1574
1575 // These six are component-wise compares with component-wise results.
1576 // Forward on to createBinaryOperation(), requesting a vector result.
1577 case glslang::EOpLessThan:
1578 case glslang::EOpGreaterThan:
1579 case glslang::EOpLessThanEqual:
1580 case glslang::EOpGreaterThanEqual:
1581 case glslang::EOpVectorEqual:
1582 case glslang::EOpVectorNotEqual:
1583 {
1584 // Map the operation to a binary
1585 binOp = node->getOp();
1586 reduceComparison = false;
1587 switch (node->getOp()) {
1588 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1589 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1590 default: binOp = node->getOp(); break;
1591 }
1592
1593 break;
1594 }
1595 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001596 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001597 binOp = glslang::EOpMul;
1598 break;
1599 case glslang::EOpOuterProduct:
1600 // two vectors multiplied to make a matrix
1601 binOp = glslang::EOpOuterProduct;
1602 break;
1603 case glslang::EOpDot:
1604 {
qining25262b32016-05-06 17:25:16 -04001605 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001606 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001607 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001608 binOp = glslang::EOpMul;
1609 break;
1610 }
1611 case glslang::EOpMod:
1612 // when an aggregate, this is the floating-point mod built-in function,
1613 // which can be emitted by the one in createBinaryOperation()
1614 binOp = glslang::EOpMod;
1615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001616 case glslang::EOpEmitVertex:
1617 case glslang::EOpEndPrimitive:
1618 case glslang::EOpBarrier:
1619 case glslang::EOpMemoryBarrier:
1620 case glslang::EOpMemoryBarrierAtomicCounter:
1621 case glslang::EOpMemoryBarrierBuffer:
1622 case glslang::EOpMemoryBarrierImage:
1623 case glslang::EOpMemoryBarrierShared:
1624 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001625 case glslang::EOpAllMemoryBarrierWithGroupSync:
1626 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1627 case glslang::EOpWorkgroupMemoryBarrier:
1628 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001629 noReturnValue = true;
1630 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1631 break;
1632
John Kessenich426394d2015-07-23 10:22:48 -06001633 case glslang::EOpAtomicAdd:
1634 case glslang::EOpAtomicMin:
1635 case glslang::EOpAtomicMax:
1636 case glslang::EOpAtomicAnd:
1637 case glslang::EOpAtomicOr:
1638 case glslang::EOpAtomicXor:
1639 case glslang::EOpAtomicExchange:
1640 case glslang::EOpAtomicCompSwap:
1641 atomic = true;
1642 break;
1643
John Kessenich140f3df2015-06-26 16:58:36 -06001644 default:
1645 break;
1646 }
1647
1648 //
1649 // See if it maps to a regular operation.
1650 //
John Kessenich140f3df2015-06-26 16:58:36 -06001651 if (binOp != glslang::EOpNull) {
1652 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1653 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1654 assert(left && right);
1655
1656 builder.clearAccessChain();
1657 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001658 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001659
1660 builder.clearAccessChain();
1661 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001662 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001663
qining25262b32016-05-06 17:25:16 -04001664 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001665 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001666 left->getType().getBasicType(), reduceComparison);
1667
1668 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001669 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 builder.clearAccessChain();
1671 builder.setAccessChainRValue(result);
1672
1673 return false;
1674 }
1675
John Kessenich426394d2015-07-23 10:22:48 -06001676 //
1677 // Create the list of operands.
1678 //
John Kessenich140f3df2015-06-26 16:58:36 -06001679 glslang::TIntermSequence& glslangOperands = node->getSequence();
1680 std::vector<spv::Id> operands;
1681 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001682 // special case l-value operands; there are just a few
1683 bool lvalue = false;
1684 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001685 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001686 case glslang::EOpModf:
1687 if (arg == 1)
1688 lvalue = true;
1689 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001690 case glslang::EOpInterpolateAtSample:
1691 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001692#ifdef AMD_EXTENSIONS
1693 case glslang::EOpInterpolateAtVertex:
1694#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001695 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001696 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001697
1698 // Does it need a swizzle inversion? If so, evaluation is inverted;
1699 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001700 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001701 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1702 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1703 }
Rex Xu7a26c172015-12-08 17:12:09 +08001704 break;
Rex Xud4782c12015-09-06 16:30:11 +08001705 case glslang::EOpAtomicAdd:
1706 case glslang::EOpAtomicMin:
1707 case glslang::EOpAtomicMax:
1708 case glslang::EOpAtomicAnd:
1709 case glslang::EOpAtomicOr:
1710 case glslang::EOpAtomicXor:
1711 case glslang::EOpAtomicExchange:
1712 case glslang::EOpAtomicCompSwap:
1713 if (arg == 0)
1714 lvalue = true;
1715 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001716 case glslang::EOpAddCarry:
1717 case glslang::EOpSubBorrow:
1718 if (arg == 2)
1719 lvalue = true;
1720 break;
1721 case glslang::EOpUMulExtended:
1722 case glslang::EOpIMulExtended:
1723 if (arg >= 2)
1724 lvalue = true;
1725 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001726 default:
1727 break;
1728 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001729 builder.clearAccessChain();
1730 if (invertedType != spv::NoType && arg == 0)
1731 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1732 else
1733 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001734 if (lvalue)
1735 operands.push_back(builder.accessChainGetLValue());
1736 else
John Kessenich32cfd492016-02-02 12:37:46 -07001737 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001738 }
John Kessenich426394d2015-07-23 10:22:48 -06001739
1740 if (atomic) {
1741 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001742 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001743 } else {
1744 // Pass through to generic operations.
1745 switch (glslangOperands.size()) {
1746 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 break;
1749 case 1:
qining25262b32016-05-06 17:25:16 -04001750 result = createUnaryOperation(
1751 node->getOp(), precision,
1752 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001753 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001754 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001755 break;
1756 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001758 break;
1759 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001760 if (invertedType)
1761 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763
1764 if (noReturnValue)
1765 return false;
1766
1767 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001768 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001769 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001770 } else {
1771 builder.clearAccessChain();
1772 builder.setAccessChainRValue(result);
1773 return false;
1774 }
1775}
1776
John Kessenich433e9ff2017-01-26 20:31:11 -07001777// This path handles both if-then-else and ?:
1778// The if-then-else has a node type of void, while
1779// ?: has either a void or a non-void node type
1780//
1781// Leaving the result, when not void:
1782// GLSL only has r-values as the result of a :?, but
1783// if we have an l-value, that can be more efficient if it will
1784// become the base of a complex r-value expression, because the
1785// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001786bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1787{
John Kessenich433e9ff2017-01-26 20:31:11 -07001788 // See if it simple and safe to generate OpSelect instead of using control flow.
1789 // Crucially, side effects must be avoided, and there are performance trade-offs.
1790 // Return true if good idea (and safe) for OpSelect, false otherwise.
1791 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001792 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1793 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001794 return false;
1795
1796 if (node->getTrueBlock() == nullptr ||
1797 node->getFalseBlock() == nullptr)
1798 return false;
1799
1800 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1801 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1802
1803 // return true if a single operand to ? : is okay for OpSelect
1804 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001805 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001806 };
1807
1808 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1809 operandOkay(node->getFalseBlock()->getAsTyped());
1810 };
1811
1812 // Emit OpSelect for this selection.
1813 const auto handleAsOpSelect = [&]() {
1814 node->getCondition()->traverse(this);
1815 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1816 node->getTrueBlock()->traverse(this);
1817 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1818 node->getFalseBlock()->traverse(this);
1819 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1820
1821 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1822 builder.clearAccessChain();
1823 builder.setAccessChainRValue(select);
1824 };
1825
1826 // Try for OpSelect
1827
1828 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001829 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1830 if (node->getType().getQualifier().isSpecConstant())
1831 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1832
John Kessenich433e9ff2017-01-26 20:31:11 -07001833 handleAsOpSelect();
1834 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001835 }
1836
John Kessenich433e9ff2017-01-26 20:31:11 -07001837 // Instead, emit control flow...
1838
1839 // Don't handle results as temporaries, because there will be two names
1840 // and better to leave SSA to later passes.
1841 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1842 ? spv::NoResult
1843 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1844
John Kessenich140f3df2015-06-26 16:58:36 -06001845 // emit the condition before doing anything with selection
1846 node->getCondition()->traverse(this);
1847
1848 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001849 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001850
John Kessenich433e9ff2017-01-26 20:31:11 -07001851 // emit the "then" statement
1852 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001853 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001854 if (result != spv::NoResult)
1855 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001856 }
1857
John Kessenich433e9ff2017-01-26 20:31:11 -07001858 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001859 ifBuilder.makeBeginElse();
1860 // emit the "else" statement
1861 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001862 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001863 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865
John Kessenich433e9ff2017-01-26 20:31:11 -07001866 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001867 ifBuilder.makeEndIf();
1868
John Kessenich433e9ff2017-01-26 20:31:11 -07001869 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001870 // GLSL only has r-values as the result of a :?, but
1871 // if we have an l-value, that can be more efficient if it will
1872 // become the base of a complex r-value expression, because the
1873 // next layer copies r-values into memory to use the access-chain mechanism
1874 builder.clearAccessChain();
1875 builder.setAccessChainLValue(result);
1876 }
1877
1878 return false;
1879}
1880
1881bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1882{
1883 // emit and get the condition before doing anything with switch
1884 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001885 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001886
1887 // browse the children to sort out code segments
1888 int defaultSegment = -1;
1889 std::vector<TIntermNode*> codeSegments;
1890 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1891 std::vector<int> caseValues;
1892 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1893 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1894 TIntermNode* child = *c;
1895 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001896 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001897 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001898 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001899 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1900 } else
1901 codeSegments.push_back(child);
1902 }
1903
qining25262b32016-05-06 17:25:16 -04001904 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001905 // statements between the last case and the end of the switch statement
1906 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1907 (int)codeSegments.size() == defaultSegment)
1908 codeSegments.push_back(nullptr);
1909
1910 // make the switch statement
1911 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001912 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001913
1914 // emit all the code in the segments
1915 breakForLoop.push(false);
1916 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1917 builder.nextSwitchSegment(segmentBlocks, s);
1918 if (codeSegments[s])
1919 codeSegments[s]->traverse(this);
1920 else
1921 builder.addSwitchBreak();
1922 }
1923 breakForLoop.pop();
1924
1925 builder.endSwitch(segmentBlocks);
1926
1927 return false;
1928}
1929
1930void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1931{
1932 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001933 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001934
1935 builder.clearAccessChain();
1936 builder.setAccessChainRValue(constant);
1937}
1938
1939bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1940{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001941 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001942 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001943 // Spec requires back edges to target header blocks, and every header block
1944 // must dominate its merge block. Make a header block first to ensure these
1945 // conditions are met. By definition, it will contain OpLoopMerge, followed
1946 // by a block-ending branch. But we don't want to put any other body/test
1947 // instructions in it, since the body/test may have arbitrary instructions,
1948 // including merges of its own.
1949 builder.setBuildPoint(&blocks.head);
1950 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001951 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001952 spv::Block& test = builder.makeNewBlock();
1953 builder.createBranch(&test);
1954
1955 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001956 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001957 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001958 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001959 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1960
1961 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001962 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001963 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001964 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001965 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001966 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001967
1968 builder.setBuildPoint(&blocks.continue_target);
1969 if (node->getTerminal())
1970 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001971 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001972 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001973 builder.createBranch(&blocks.body);
1974
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001975 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 builder.setBuildPoint(&blocks.body);
1977 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001978 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001979 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001980 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001981
1982 builder.setBuildPoint(&blocks.continue_target);
1983 if (node->getTerminal())
1984 node->getTerminal()->traverse(this);
1985 if (node->getTest()) {
1986 node->getTest()->traverse(this);
1987 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001988 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001989 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001990 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001991 // TODO: unless there was a break/return/discard instruction
1992 // somewhere in the body, this is an infinite loop, so we should
1993 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001994 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001995 }
John Kessenich140f3df2015-06-26 16:58:36 -06001996 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001997 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001998 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001999 return false;
2000}
2001
2002bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2003{
2004 if (node->getExpression())
2005 node->getExpression()->traverse(this);
2006
2007 switch (node->getFlowOp()) {
2008 case glslang::EOpKill:
2009 builder.makeDiscard();
2010 break;
2011 case glslang::EOpBreak:
2012 if (breakForLoop.top())
2013 builder.createLoopExit();
2014 else
2015 builder.addSwitchBreak();
2016 break;
2017 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002018 builder.createLoopContinue();
2019 break;
2020 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002021 if (node->getExpression()) {
2022 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2023 spv::Id returnId = accessChainLoad(glslangReturnType);
2024 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2025 builder.clearAccessChain();
2026 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2027 builder.setAccessChainLValue(copyId);
2028 multiTypeStore(glslangReturnType, returnId);
2029 returnId = builder.createLoad(copyId);
2030 }
2031 builder.makeReturn(false, returnId);
2032 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002033 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002034
2035 builder.clearAccessChain();
2036 break;
2037
2038 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002039 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002040 break;
2041 }
2042
2043 return false;
2044}
2045
2046spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2047{
qining25262b32016-05-06 17:25:16 -04002048 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002049 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002050 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002051 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002052 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002053 }
2054
2055 // Now, handle actual variables
2056 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2057 spv::Id spvType = convertGlslangToSpvType(node->getType());
2058
2059 const char* name = node->getName().c_str();
2060 if (glslang::IsAnonymous(name))
2061 name = "";
2062
2063 return builder.createVariable(storageClass, spvType, name);
2064}
2065
2066// Return type Id of the sampled type.
2067spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2068{
2069 switch (sampler.type) {
2070 case glslang::EbtFloat: return builder.makeFloatType(32);
2071 case glslang::EbtInt: return builder.makeIntType(32);
2072 case glslang::EbtUint: return builder.makeUintType(32);
2073 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002074 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002075 return builder.makeFloatType(32);
2076 }
2077}
2078
John Kessenich8c8505c2016-07-26 12:50:38 -06002079// If node is a swizzle operation, return the type that should be used if
2080// the swizzle base is first consumed by another operation, before the swizzle
2081// is applied.
2082spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2083{
John Kessenichecba76f2017-01-06 00:34:48 -07002084 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002085 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2086 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2087 else
2088 return spv::NoType;
2089}
2090
2091// When inverting a swizzle with a parent op, this function
2092// will apply the swizzle operation to a completed parent operation.
2093spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2094{
2095 std::vector<unsigned> swizzle;
2096 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2097 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2098}
2099
John Kessenich8c8505c2016-07-26 12:50:38 -06002100// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2101void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2102{
2103 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2104 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2105 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2106}
2107
John Kessenich3ac051e2015-12-20 11:29:16 -07002108// Convert from a glslang type to an SPV type, by calling into a
2109// recursive version of this function. This establishes the inherited
2110// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002111spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2112{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002113 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002114}
2115
2116// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002117// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002118// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002119spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002120{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002121 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002122
2123 switch (type.getBasicType()) {
2124 case glslang::EbtVoid:
2125 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002126 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002127 break;
2128 case glslang::EbtFloat:
2129 spvType = builder.makeFloatType(32);
2130 break;
2131 case glslang::EbtDouble:
2132 spvType = builder.makeFloatType(64);
2133 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002134#ifdef AMD_EXTENSIONS
2135 case glslang::EbtFloat16:
2136 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002137 spvType = builder.makeFloatType(16);
2138 break;
2139#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002140 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002141 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2142 // a 32-bit int where non-0 means true.
2143 if (explicitLayout != glslang::ElpNone)
2144 spvType = builder.makeUintType(32);
2145 else
2146 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002147 break;
2148 case glslang::EbtInt:
2149 spvType = builder.makeIntType(32);
2150 break;
2151 case glslang::EbtUint:
2152 spvType = builder.makeUintType(32);
2153 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002154 case glslang::EbtInt64:
2155 builder.addCapability(spv::CapabilityInt64);
2156 spvType = builder.makeIntType(64);
2157 break;
2158 case glslang::EbtUint64:
2159 builder.addCapability(spv::CapabilityInt64);
2160 spvType = builder.makeUintType(64);
2161 break;
John Kessenich426394d2015-07-23 10:22:48 -06002162 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002163 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002164 spvType = builder.makeUintType(32);
2165 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002166 case glslang::EbtSampler:
2167 {
2168 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002169 if (sampler.sampler) {
2170 // pure sampler
2171 spvType = builder.makeSamplerType();
2172 } else {
2173 // an image is present, make its type
2174 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2175 sampler.image ? 2 : 1, TranslateImageFormat(type));
2176 if (sampler.combined) {
2177 // already has both image and sampler, make the combined type
2178 spvType = builder.makeSampledImageType(spvType);
2179 }
John Kessenich55e7d112015-11-15 21:33:39 -07002180 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002181 }
John Kessenich140f3df2015-06-26 16:58:36 -06002182 break;
2183 case glslang::EbtStruct:
2184 case glslang::EbtBlock:
2185 {
2186 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002187 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002188
2189 // Try to share structs for different layouts, but not yet for other
2190 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002191 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002192 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002193 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002194 break;
2195
2196 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002197 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002198 memberRemapper[glslangMembers].resize(glslangMembers->size());
2199 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002200 }
2201 break;
2202 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002203 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002204 break;
2205 }
2206
2207 if (type.isMatrix())
2208 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2209 else {
2210 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2211 if (type.getVectorSize() > 1)
2212 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2213 }
2214
2215 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002216 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2217
John Kessenichc9a80832015-09-12 12:17:44 -06002218 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002219 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002220 // We need to decorate array strides for types needing explicit layout, except blocks.
2221 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002222 // Use a dummy glslang type for querying internal strides of
2223 // arrays of arrays, but using just a one-dimensional array.
2224 glslang::TType simpleArrayType(type, 0); // deference type of the array
2225 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2226 simpleArrayType.getArraySizes().dereference();
2227
2228 // Will compute the higher-order strides here, rather than making a whole
2229 // pile of types and doing repetitive recursion on their contents.
2230 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2231 }
John Kessenichf8842e52016-01-04 19:22:56 -07002232
2233 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002234 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002235 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002236 if (stride > 0)
2237 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002238 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002239 }
2240 } else {
2241 // single-dimensional array, and don't yet have stride
2242
John Kessenichf8842e52016-01-04 19:22:56 -07002243 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002244 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2245 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002246 }
John Kessenich31ed4832015-09-09 17:51:38 -06002247
John Kessenichc9a80832015-09-12 12:17:44 -06002248 // Do the outer dimension, which might not be known for a runtime-sized array
2249 if (type.isRuntimeSizedArray()) {
2250 spvType = builder.makeRuntimeArray(spvType);
2251 } else {
2252 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002253 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002254 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002255 if (stride > 0)
2256 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002257 }
2258
2259 return spvType;
2260}
2261
John Kessenich6090df02016-06-30 21:18:02 -06002262// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2263// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2264// Mutually recursive with convertGlslangToSpvType().
2265spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2266 const glslang::TTypeList* glslangMembers,
2267 glslang::TLayoutPacking explicitLayout,
2268 const glslang::TQualifier& qualifier)
2269{
2270 // Create a vector of struct types for SPIR-V to consume
2271 std::vector<spv::Id> spvMembers;
2272 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2273 int locationOffset = 0; // for use across struct members, when they are called recursively
2274 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2275 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2276 if (glslangMember.hiddenMember()) {
2277 ++memberDelta;
2278 if (type.getBasicType() == glslang::EbtBlock)
2279 memberRemapper[glslangMembers][i] = -1;
2280 } else {
2281 if (type.getBasicType() == glslang::EbtBlock)
2282 memberRemapper[glslangMembers][i] = i - memberDelta;
2283 // modify just this child's view of the qualifier
2284 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2285 InheritQualifiers(memberQualifier, qualifier);
2286
2287 // manually inherit location; it's more complex
2288 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2289 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2290 if (qualifier.hasLocation())
2291 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2292
2293 // recurse
2294 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2295 }
2296 }
2297
2298 // Make the SPIR-V type
2299 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002300 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002301 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2302
2303 // Decorate it
2304 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2305
2306 return spvType;
2307}
2308
2309void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2310 const glslang::TTypeList* glslangMembers,
2311 glslang::TLayoutPacking explicitLayout,
2312 const glslang::TQualifier& qualifier,
2313 spv::Id spvType)
2314{
2315 // Name and decorate the non-hidden members
2316 int offset = -1;
2317 int locationOffset = 0; // for use within the members of this struct
2318 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2319 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2320 int member = i;
2321 if (type.getBasicType() == glslang::EbtBlock)
2322 member = memberRemapper[glslangMembers][i];
2323
2324 // modify just this child's view of the qualifier
2325 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2326 InheritQualifiers(memberQualifier, qualifier);
2327
2328 // using -1 above to indicate a hidden member
2329 if (member >= 0) {
2330 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2331 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2332 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2333 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002334 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2335 type.getQualifier().storage == glslang::EvqVaryingOut) {
2336 if (type.getBasicType() == glslang::EbtBlock ||
2337 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002338 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2339 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2340 }
2341 }
2342 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2343
2344 if (qualifier.storage == glslang::EvqBuffer) {
2345 std::vector<spv::Decoration> memory;
2346 TranslateMemoryDecoration(memberQualifier, memory);
2347 for (unsigned int i = 0; i < memory.size(); ++i)
2348 addMemberDecoration(spvType, member, memory[i]);
2349 }
2350
John Kessenich2f47bc92016-06-30 21:47:35 -06002351 // Compute location decoration; tricky based on whether inheritance is at play and
2352 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002353 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2354 // probably move to the linker stage of the front end proper, and just have the
2355 // answer sitting already distributed throughout the individual member locations.
2356 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002357 // Ignore member locations if the container is an array, as that's
2358 // ill-specified and decisions have been made to not allow this anyway.
2359 // The object itself must have a location, and that comes out from decorating the object,
2360 // not the type (this code decorates types).
2361 if (! type.isArray()) {
2362 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2363 // struct members should not have explicit locations
2364 assert(type.getBasicType() != glslang::EbtStruct);
2365 location = memberQualifier.layoutLocation;
2366 } else if (type.getBasicType() != glslang::EbtBlock) {
2367 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2368 // The members, and their nested types, must not themselves have Location decorations.
2369 } else if (qualifier.hasLocation()) // inheritance
2370 location = qualifier.layoutLocation + locationOffset;
2371 }
John Kessenich6090df02016-06-30 21:18:02 -06002372 if (location >= 0)
2373 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2374
John Kessenich2f47bc92016-06-30 21:47:35 -06002375 if (qualifier.hasLocation()) // track for upcoming inheritance
2376 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2377
John Kessenich6090df02016-06-30 21:18:02 -06002378 // component, XFB, others
2379 if (glslangMember.getQualifier().hasComponent())
2380 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2381 if (glslangMember.getQualifier().hasXfbOffset())
2382 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2383 else if (explicitLayout != glslang::ElpNone) {
2384 // figure out what to do with offset, which is accumulating
2385 int nextOffset;
2386 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2387 if (offset >= 0)
2388 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2389 offset = nextOffset;
2390 }
2391
2392 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2393 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2394
2395 // built-in variable decorations
2396 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002397 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002398 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002399
2400#ifdef NV_EXTENSIONS
2401 if (builtIn == spv::BuiltInLayer) {
2402 // SPV_NV_viewport_array2 extension
2403 if (glslangMember.getQualifier().layoutViewportRelative){
2404 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2405 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2406 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2407 }
2408 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2409 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2410 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2411 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2412 }
2413 }
chaocdf3956c2017-02-14 14:52:34 -08002414 if (glslangMember.getQualifier().layoutPassthrough) {
2415 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2416 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2417 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2418 }
chaoc771d89f2017-01-13 01:10:53 -08002419#endif
John Kessenich6090df02016-06-30 21:18:02 -06002420 }
2421 }
2422
2423 // Decorate the structure
2424 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2425 addDecoration(spvType, TranslateBlockDecoration(type));
2426 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2427 builder.addCapability(spv::CapabilityGeometryStreams);
2428 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2429 }
2430 if (glslangIntermediate->getXfbMode()) {
2431 builder.addCapability(spv::CapabilityTransformFeedback);
2432 if (type.getQualifier().hasXfbStride())
2433 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2434 if (type.getQualifier().hasXfbBuffer())
2435 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2436 }
2437}
2438
John Kessenich6c292d32016-02-15 20:58:50 -07002439// Turn the expression forming the array size into an id.
2440// This is not quite trivial, because of specialization constants.
2441// Sometimes, a raw constant is turned into an Id, and sometimes
2442// a specialization constant expression is.
2443spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2444{
2445 // First, see if this is sized with a node, meaning a specialization constant:
2446 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2447 if (specNode != nullptr) {
2448 builder.clearAccessChain();
2449 specNode->traverse(this);
2450 return accessChainLoad(specNode->getAsTyped()->getType());
2451 }
qining25262b32016-05-06 17:25:16 -04002452
John Kessenich6c292d32016-02-15 20:58:50 -07002453 // Otherwise, need a compile-time (front end) size, get it:
2454 int size = arraySizes.getDimSize(dim);
2455 assert(size > 0);
2456 return builder.makeUintConstant(size);
2457}
2458
John Kessenich103bef92016-02-08 21:38:15 -07002459// Wrap the builder's accessChainLoad to:
2460// - localize handling of RelaxedPrecision
2461// - use the SPIR-V inferred type instead of another conversion of the glslang type
2462// (avoids unnecessary work and possible type punning for structures)
2463// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002464spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2465{
John Kessenich103bef92016-02-08 21:38:15 -07002466 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2467 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2468
2469 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002470 if (type.getBasicType() == glslang::EbtBool) {
2471 if (builder.isScalarType(nominalTypeId)) {
2472 // Conversion for bool
2473 spv::Id boolType = builder.makeBoolType();
2474 if (nominalTypeId != boolType)
2475 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2476 } else if (builder.isVectorType(nominalTypeId)) {
2477 // Conversion for bvec
2478 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2479 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2480 if (nominalTypeId != bvecType)
2481 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2482 }
2483 }
John Kessenich103bef92016-02-08 21:38:15 -07002484
2485 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002486}
2487
Rex Xu27253232016-02-23 17:51:09 +08002488// Wrap the builder's accessChainStore to:
2489// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002490//
2491// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002492void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2493{
2494 // Need to convert to abstract types when necessary
2495 if (type.getBasicType() == glslang::EbtBool) {
2496 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2497
2498 if (builder.isScalarType(nominalTypeId)) {
2499 // Conversion for bool
2500 spv::Id boolType = builder.makeBoolType();
2501 if (nominalTypeId != boolType) {
2502 spv::Id zero = builder.makeUintConstant(0);
2503 spv::Id one = builder.makeUintConstant(1);
2504 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2505 }
2506 } else if (builder.isVectorType(nominalTypeId)) {
2507 // Conversion for bvec
2508 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2509 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2510 if (nominalTypeId != bvecType) {
2511 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2512 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2513 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2514 }
2515 }
2516 }
2517
2518 builder.accessChainStore(rvalue);
2519}
2520
John Kessenich4bf71552016-09-02 11:20:21 -06002521// For storing when types match at the glslang level, but not might match at the
2522// SPIR-V level.
2523//
2524// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002525// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002526// as in a member-decorated way.
2527//
2528// NOTE: This function can handle any store request; if it's not special it
2529// simplifies to a simple OpStore.
2530//
2531// Implicitly uses the existing builder.accessChain as the storage target.
2532void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2533{
John Kessenichb3e24e42016-09-11 12:33:43 -06002534 // we only do the complex path here if it's an aggregate
2535 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002536 accessChainStore(type, rValue);
2537 return;
2538 }
2539
John Kessenichb3e24e42016-09-11 12:33:43 -06002540 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002541 spv::Id rType = builder.getTypeId(rValue);
2542 spv::Id lValue = builder.accessChainGetLValue();
2543 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2544 if (lType == rType) {
2545 accessChainStore(type, rValue);
2546 return;
2547 }
2548
John Kessenichb3e24e42016-09-11 12:33:43 -06002549 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002550 // where the two types were the same type in GLSL. This requires member
2551 // by member copy, recursively.
2552
John Kessenichb3e24e42016-09-11 12:33:43 -06002553 // If an array, copy element by element.
2554 if (type.isArray()) {
2555 glslang::TType glslangElementType(type, 0);
2556 spv::Id elementRType = builder.getContainedTypeId(rType);
2557 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2558 // get the source member
2559 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002560
John Kessenichb3e24e42016-09-11 12:33:43 -06002561 // set up the target storage
2562 builder.clearAccessChain();
2563 builder.setAccessChainLValue(lValue);
2564 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002565
John Kessenichb3e24e42016-09-11 12:33:43 -06002566 // store the member
2567 multiTypeStore(glslangElementType, elementRValue);
2568 }
2569 } else {
2570 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002571
John Kessenichb3e24e42016-09-11 12:33:43 -06002572 // loop over structure members
2573 const glslang::TTypeList& members = *type.getStruct();
2574 for (int m = 0; m < (int)members.size(); ++m) {
2575 const glslang::TType& glslangMemberType = *members[m].type;
2576
2577 // get the source member
2578 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2579 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2580
2581 // set up the target storage
2582 builder.clearAccessChain();
2583 builder.setAccessChainLValue(lValue);
2584 builder.accessChainPush(builder.makeIntConstant(m));
2585
2586 // store the member
2587 multiTypeStore(glslangMemberType, memberRValue);
2588 }
John Kessenich4bf71552016-09-02 11:20:21 -06002589 }
2590}
2591
John Kessenichf85e8062015-12-19 13:57:10 -07002592// Decide whether or not this type should be
2593// decorated with offsets and strides, and if so
2594// whether std140 or std430 rules should be applied.
2595glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002596{
John Kessenichf85e8062015-12-19 13:57:10 -07002597 // has to be a block
2598 if (type.getBasicType() != glslang::EbtBlock)
2599 return glslang::ElpNone;
2600
2601 // has to be a uniform or buffer block
2602 if (type.getQualifier().storage != glslang::EvqUniform &&
2603 type.getQualifier().storage != glslang::EvqBuffer)
2604 return glslang::ElpNone;
2605
2606 // return the layout to use
2607 switch (type.getQualifier().layoutPacking) {
2608 case glslang::ElpStd140:
2609 case glslang::ElpStd430:
2610 return type.getQualifier().layoutPacking;
2611 default:
2612 return glslang::ElpNone;
2613 }
John Kessenich31ed4832015-09-09 17:51:38 -06002614}
2615
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002616// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002617int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002618{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002619 int size;
John Kessenich49987892015-12-29 17:11:44 -07002620 int stride;
2621 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002622
2623 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002624}
2625
John Kessenich49987892015-12-29 17:11:44 -07002626// 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 -07002627// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002628int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002629{
John Kessenich49987892015-12-29 17:11:44 -07002630 glslang::TType elementType;
2631 elementType.shallowCopy(matrixType);
2632 elementType.clearArraySizes();
2633
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002634 int size;
John Kessenich49987892015-12-29 17:11:44 -07002635 int stride;
2636 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2637
2638 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002639}
2640
John Kessenich5e4b1242015-08-06 22:53:06 -06002641// Given a member type of a struct, realign the current offset for it, and compute
2642// the next (not yet aligned) offset for the next member, which will get aligned
2643// on the next call.
2644// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2645// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2646// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002647void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002648 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002649{
2650 // this will get a positive value when deemed necessary
2651 nextOffset = -1;
2652
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 // override anything in currentOffset with user-set offset
2654 if (memberType.getQualifier().hasOffset())
2655 currentOffset = memberType.getQualifier().layoutOffset;
2656
2657 // It could be that current linker usage in glslang updated all the layoutOffset,
2658 // in which case the following code does not matter. But, that's not quite right
2659 // once cross-compilation unit GLSL validation is done, as the original user
2660 // settings are needed in layoutOffset, and then the following will come into play.
2661
John Kessenichf85e8062015-12-19 13:57:10 -07002662 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 if (! memberType.getQualifier().hasOffset())
2664 currentOffset = -1;
2665
2666 return;
2667 }
2668
John Kessenichf85e8062015-12-19 13:57:10 -07002669 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002670 if (currentOffset < 0)
2671 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002672
John Kessenich5e4b1242015-08-06 22:53:06 -06002673 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2674 // but possibly not yet correctly aligned.
2675
2676 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002677 int dummyStride;
2678 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002679 glslang::RoundToPow2(currentOffset, memberAlignment);
2680 nextOffset = currentOffset + memberSize;
2681}
2682
David Netoa901ffe2016-06-08 14:11:40 +01002683void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002684{
David Netoa901ffe2016-06-08 14:11:40 +01002685 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2686 switch (glslangBuiltIn)
2687 {
2688 case glslang::EbvClipDistance:
2689 case glslang::EbvCullDistance:
2690 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002691#ifdef NV_EXTENSIONS
2692 case glslang::EbvLayer:
2693 case glslang::EbvViewportMaskNV:
2694 case glslang::EbvSecondaryPositionNV:
2695 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002696 case glslang::EbvPositionPerViewNV:
2697 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002698#endif
David Netoa901ffe2016-06-08 14:11:40 +01002699 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2700 // Alternately, we could just call this for any glslang built-in, since the
2701 // capability already guards against duplicates.
2702 TranslateBuiltInDecoration(glslangBuiltIn, false);
2703 break;
2704 default:
2705 // Capabilities were already generated when the struct was declared.
2706 break;
2707 }
John Kessenichebb50532016-05-16 19:22:05 -06002708}
2709
John Kessenich6fccb3c2016-09-19 16:01:41 -06002710bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002711{
John Kessenicheee9d532016-09-19 18:09:30 -06002712 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002713}
2714
2715// Make all the functions, skeletally, without actually visiting their bodies.
2716void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2717{
2718 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2719 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002720 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002721 continue;
2722
2723 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002724 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002725 //
qining25262b32016-05-06 17:25:16 -04002726 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002727 // function. What it is an address of varies:
2728 //
John Kessenich4bf71552016-09-02 11:20:21 -06002729 // - "in" parameters not marked as "const" can be written to without modifying the calling
2730 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002731 //
2732 // - "const in" parameters can just be the r-value, as no writes need occur.
2733 //
John Kessenich4bf71552016-09-02 11:20:21 -06002734 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2735 // 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 -06002736
2737 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002738 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2740
2741 for (int p = 0; p < (int)parameters.size(); ++p) {
2742 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2743 spv::Id typeId = convertGlslangToSpvType(paramType);
steve-lunargdd8287a2017-02-23 18:04:12 -07002744 if (paramType.containsOpaque() ||
2745 (paramType.getBasicType() == glslang::EbtBlock && paramType.getQualifier().storage == glslang::EvqBuffer))
Jason Ekstranded15ef12016-06-08 13:54:48 -07002746 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2747 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002748 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2749 else
John Kessenich4bf71552016-09-02 11:20:21 -06002750 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002751 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002752 paramTypes.push_back(typeId);
2753 }
2754
2755 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002756 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2757 convertGlslangToSpvType(glslFunction->getType()),
2758 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002759
2760 // Track function to emit/call later
2761 functionMap[glslFunction->getName().c_str()] = function;
2762
2763 // Set the parameter id's
2764 for (int p = 0; p < (int)parameters.size(); ++p) {
2765 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2766 // give a name too
2767 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2768 }
2769 }
2770}
2771
2772// Process all the initializers, while skipping the functions and link objects
2773void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2774{
2775 builder.setBuildPoint(shaderEntry->getLastBlock());
2776 for (int i = 0; i < (int)initializers.size(); ++i) {
2777 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2778 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2779
2780 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002781 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002782 initializer->traverse(this);
2783 }
2784 }
2785}
2786
2787// Process all the functions, while skipping initializers.
2788void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2789{
2790 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2791 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002792 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002793 node->traverse(this);
2794 }
2795}
2796
2797void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2798{
qining25262b32016-05-06 17:25:16 -04002799 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002800 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002801 currentFunction = functionMap[node->getName().c_str()];
2802 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002803 builder.setBuildPoint(functionBlock);
2804}
2805
Rex Xu04db3f52015-09-16 11:44:02 +08002806void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002807{
Rex Xufc618912015-09-09 16:42:49 +08002808 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002809
2810 glslang::TSampler sampler = {};
2811 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002812 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002813 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2814 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2815 }
2816
John Kessenich140f3df2015-06-26 16:58:36 -06002817 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2818 builder.clearAccessChain();
2819 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002820
2821 // Special case l-value operands
2822 bool lvalue = false;
2823 switch (node.getOp()) {
2824 case glslang::EOpImageAtomicAdd:
2825 case glslang::EOpImageAtomicMin:
2826 case glslang::EOpImageAtomicMax:
2827 case glslang::EOpImageAtomicAnd:
2828 case glslang::EOpImageAtomicOr:
2829 case glslang::EOpImageAtomicXor:
2830 case glslang::EOpImageAtomicExchange:
2831 case glslang::EOpImageAtomicCompSwap:
2832 if (i == 0)
2833 lvalue = true;
2834 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002835 case glslang::EOpSparseImageLoad:
2836 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2837 lvalue = true;
2838 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002839 case glslang::EOpSparseTexture:
2840 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2841 lvalue = true;
2842 break;
2843 case glslang::EOpSparseTextureClamp:
2844 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2845 lvalue = true;
2846 break;
2847 case glslang::EOpSparseTextureLod:
2848 case glslang::EOpSparseTextureOffset:
2849 if (i == 3)
2850 lvalue = true;
2851 break;
2852 case glslang::EOpSparseTextureFetch:
2853 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2854 lvalue = true;
2855 break;
2856 case glslang::EOpSparseTextureFetchOffset:
2857 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2858 lvalue = true;
2859 break;
2860 case glslang::EOpSparseTextureLodOffset:
2861 case glslang::EOpSparseTextureGrad:
2862 case glslang::EOpSparseTextureOffsetClamp:
2863 if (i == 4)
2864 lvalue = true;
2865 break;
2866 case glslang::EOpSparseTextureGradOffset:
2867 case glslang::EOpSparseTextureGradClamp:
2868 if (i == 5)
2869 lvalue = true;
2870 break;
2871 case glslang::EOpSparseTextureGradOffsetClamp:
2872 if (i == 6)
2873 lvalue = true;
2874 break;
2875 case glslang::EOpSparseTextureGather:
2876 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2877 lvalue = true;
2878 break;
2879 case glslang::EOpSparseTextureGatherOffset:
2880 case glslang::EOpSparseTextureGatherOffsets:
2881 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2882 lvalue = true;
2883 break;
Rex Xufc618912015-09-09 16:42:49 +08002884 default:
2885 break;
2886 }
2887
Rex Xu6b86d492015-09-16 17:48:22 +08002888 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002889 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002890 else
John Kessenich32cfd492016-02-02 12:37:46 -07002891 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002892 }
2893}
2894
John Kessenichfc51d282015-08-19 13:34:18 -06002895void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002896{
John Kessenichfc51d282015-08-19 13:34:18 -06002897 builder.clearAccessChain();
2898 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002899 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002900}
John Kessenich140f3df2015-06-26 16:58:36 -06002901
John Kessenichfc51d282015-08-19 13:34:18 -06002902spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2903{
Rex Xufc618912015-09-09 16:42:49 +08002904 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002905 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002906 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002907 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002908
John Kessenichfc51d282015-08-19 13:34:18 -06002909 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002910 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2911 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2912 std::vector<spv::Id> arguments;
2913 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002914 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002915 else
2916 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002917 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002918
2919 spv::Builder::TextureParameters params = { };
2920 params.sampler = arguments[0];
2921
Rex Xu04db3f52015-09-16 11:44:02 +08002922 glslang::TCrackedTextureOp cracked;
2923 node->crackTexture(sampler, cracked);
2924
John Kessenichfc51d282015-08-19 13:34:18 -06002925 // Check for queries
2926 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002927 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2928 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002929 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002930
John Kessenichfc51d282015-08-19 13:34:18 -06002931 switch (node->getOp()) {
2932 case glslang::EOpImageQuerySize:
2933 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002934 if (arguments.size() > 1) {
2935 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002936 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002937 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002938 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002939 case glslang::EOpImageQuerySamples:
2940 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002941 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002942 case glslang::EOpTextureQueryLod:
2943 params.coords = arguments[1];
2944 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2945 case glslang::EOpTextureQueryLevels:
2946 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002947 case glslang::EOpSparseTexelsResident:
2948 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002949 default:
2950 assert(0);
2951 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002952 }
John Kessenich140f3df2015-06-26 16:58:36 -06002953 }
2954
Rex Xufc618912015-09-09 16:42:49 +08002955 // Check for image functions other than queries
2956 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002957 std::vector<spv::Id> operands;
2958 auto opIt = arguments.begin();
2959 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002960
2961 // Handle subpass operations
2962 // TODO: GLSL should change to have the "MS" only on the type rather than the
2963 // built-in function.
2964 if (cracked.subpass) {
2965 // add on the (0,0) coordinate
2966 spv::Id zero = builder.makeIntConstant(0);
2967 std::vector<spv::Id> comps;
2968 comps.push_back(zero);
2969 comps.push_back(zero);
2970 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2971 if (sampler.ms) {
2972 operands.push_back(spv::ImageOperandsSampleMask);
2973 operands.push_back(*(opIt++));
2974 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002975 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002976 }
2977
John Kessenich56bab042015-09-16 10:54:31 -06002978 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002979 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002980 if (sampler.ms) {
2981 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002982 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002983 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002984 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2985 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002986 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002987 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002988 if (sampler.ms) {
2989 operands.push_back(*(opIt + 1));
2990 operands.push_back(spv::ImageOperandsSampleMask);
2991 operands.push_back(*opIt);
2992 } else
2993 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002994 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002995 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2996 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002997 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002998 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2999 builder.addCapability(spv::CapabilitySparseResidency);
3000 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3001 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3002
3003 if (sampler.ms) {
3004 operands.push_back(spv::ImageOperandsSampleMask);
3005 operands.push_back(*opIt++);
3006 }
3007
3008 // Create the return type that was a special structure
3009 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003010 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003011 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3012 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3013
3014 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3015
3016 // Decode the return type
3017 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3018 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003019 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003020 // Process image atomic operations
3021
3022 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3023 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003024 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003025
John Kessenich8c8505c2016-07-26 12:50:38 -06003026 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003027 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003028
3029 std::vector<spv::Id> operands;
3030 operands.push_back(pointer);
3031 for (; opIt != arguments.end(); ++opIt)
3032 operands.push_back(*opIt);
3033
John Kessenich8c8505c2016-07-26 12:50:38 -06003034 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003035 }
3036 }
3037
3038 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003039 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003040 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3041
John Kessenichfc51d282015-08-19 13:34:18 -06003042 // check for bias argument
3043 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003044 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003045 int nonBiasArgCount = 2;
3046 if (cracked.offset)
3047 ++nonBiasArgCount;
3048 if (cracked.grad)
3049 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003050 if (cracked.lodClamp)
3051 ++nonBiasArgCount;
3052 if (sparse)
3053 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003054
3055 if ((int)arguments.size() > nonBiasArgCount)
3056 bias = true;
3057 }
3058
John Kessenicha5c33d62016-06-02 23:45:21 -06003059 // See if the sampler param should really be just the SPV image part
3060 if (cracked.fetch) {
3061 // a fetch needs to have the image extracted first
3062 if (builder.isSampledImage(params.sampler))
3063 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3064 }
3065
John Kessenichfc51d282015-08-19 13:34:18 -06003066 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003067
John Kessenichfc51d282015-08-19 13:34:18 -06003068 params.coords = arguments[1];
3069 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003070 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003071
3072 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003073 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003074 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003075 ++extraArgs;
3076 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003077 params.Dref = arguments[2];
3078 ++extraArgs;
3079 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003080 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003081 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003082 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003083 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003084 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003085 dRefComp = builder.getNumComponents(params.coords) - 1;
3086 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003087 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3088 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003089
3090 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003091 if (cracked.lod) {
3092 params.lod = arguments[2];
3093 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003094 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3095 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3096 noImplicitLod = true;
3097 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003098
3099 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003100 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003101 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003102 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003103 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003104
3105 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003106 if (cracked.grad) {
3107 params.gradX = arguments[2 + extraArgs];
3108 params.gradY = arguments[3 + extraArgs];
3109 extraArgs += 2;
3110 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003111
3112 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003113 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003114 params.offset = arguments[2 + extraArgs];
3115 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003116 } else if (cracked.offsets) {
3117 params.offsets = arguments[2 + extraArgs];
3118 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003119 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003120
3121 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003122 if (cracked.lodClamp) {
3123 params.lodClamp = arguments[2 + extraArgs];
3124 ++extraArgs;
3125 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003126
3127 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003128 if (sparse) {
3129 params.texelOut = arguments[2 + extraArgs];
3130 ++extraArgs;
3131 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003132
3133 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003134 if (bias) {
3135 params.bias = arguments[2 + extraArgs];
3136 ++extraArgs;
3137 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003138
3139 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003140 if (cracked.gather && ! sampler.shadow) {
3141 // default component is 0, if missing, otherwise an argument
3142 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003143 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003144 ++extraArgs;
3145 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003146 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003147 }
3148 }
John Kessenichfc51d282015-08-19 13:34:18 -06003149
John Kessenich65336482016-06-16 14:06:26 -06003150 // projective component (might not to move)
3151 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3152 // are divided by the last component of P."
3153 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3154 // unused components will appear after all used components."
3155 if (cracked.proj) {
3156 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3157 int projTargetComp;
3158 switch (sampler.dim) {
3159 case glslang::Esd1D: projTargetComp = 1; break;
3160 case glslang::Esd2D: projTargetComp = 2; break;
3161 case glslang::EsdRect: projTargetComp = 2; break;
3162 default: projTargetComp = projSourceComp; break;
3163 }
3164 // copy the projective coordinate if we have to
3165 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003166 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003167 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3168 projSourceComp);
3169 params.coords = builder.createCompositeInsert(projComp, params.coords,
3170 builder.getTypeId(params.coords), projTargetComp);
3171 }
3172 }
3173
John Kessenich8c8505c2016-07-26 12:50:38 -06003174 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003175}
3176
3177spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3178{
3179 // Grab the function's pointer from the previously created function
3180 spv::Function* function = functionMap[node->getName().c_str()];
3181 if (! function)
3182 return 0;
3183
3184 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3185 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3186
3187 // See comments in makeFunctions() for details about the semantics for parameter passing.
3188 //
3189 // These imply we need a four step process:
3190 // 1. Evaluate the arguments
3191 // 2. Allocate and make copies of in, out, and inout arguments
3192 // 3. Make the call
3193 // 4. Copy back the results
3194
3195 // 1. Evaluate the arguments
3196 std::vector<spv::Builder::AccessChain> lValues;
3197 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003198 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003199 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003200 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003201 // build l-value
3202 builder.clearAccessChain();
3203 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003204 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003205 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003206 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003207 // save l-value
3208 lValues.push_back(builder.getAccessChain());
3209 } else {
3210 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003211 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003212 }
3213 }
3214
3215 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3216 // copy the original into that space.
3217 //
3218 // Also, build up the list of actual arguments to pass in for the call
3219 int lValueCount = 0;
3220 int rValueCount = 0;
3221 std::vector<spv::Id> spvArgs;
3222 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003223 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003224 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003225 if (paramType.containsOpaque() ||
3226 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003227 builder.setAccessChain(lValues[lValueCount]);
3228 arg = builder.accessChainGetLValue();
3229 ++lValueCount;
3230 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003231 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003232 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3233 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3234 // need to copy the input into output space
3235 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003236 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003237 builder.clearAccessChain();
3238 builder.setAccessChainLValue(arg);
3239 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003240 }
3241 ++lValueCount;
3242 } else {
3243 arg = rValues[rValueCount];
3244 ++rValueCount;
3245 }
3246 spvArgs.push_back(arg);
3247 }
3248
3249 // 3. Make the call.
3250 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003251 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003252
3253 // 4. Copy back out an "out" arguments.
3254 lValueCount = 0;
3255 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003256 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003257 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3258 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3259 spv::Id copy = builder.createLoad(spvArgs[a]);
3260 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003261 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 }
3263 ++lValueCount;
3264 }
3265 }
3266
3267 return result;
3268}
3269
3270// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003271spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3272 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003273 spv::Id typeId, spv::Id left, spv::Id right,
3274 glslang::TBasicType typeProxy, bool reduceComparison)
3275{
Rex Xu8ff43de2016-04-22 16:51:45 +08003276 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003277#ifdef AMD_EXTENSIONS
3278 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3279#else
John Kessenich140f3df2015-06-26 16:58:36 -06003280 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003281#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003282 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003283
3284 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003285 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003286 bool comparison = false;
3287
3288 switch (op) {
3289 case glslang::EOpAdd:
3290 case glslang::EOpAddAssign:
3291 if (isFloat)
3292 binOp = spv::OpFAdd;
3293 else
3294 binOp = spv::OpIAdd;
3295 break;
3296 case glslang::EOpSub:
3297 case glslang::EOpSubAssign:
3298 if (isFloat)
3299 binOp = spv::OpFSub;
3300 else
3301 binOp = spv::OpISub;
3302 break;
3303 case glslang::EOpMul:
3304 case glslang::EOpMulAssign:
3305 if (isFloat)
3306 binOp = spv::OpFMul;
3307 else
3308 binOp = spv::OpIMul;
3309 break;
3310 case glslang::EOpVectorTimesScalar:
3311 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003312 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003313 if (builder.isVector(right))
3314 std::swap(left, right);
3315 assert(builder.isScalar(right));
3316 needMatchingVectors = false;
3317 binOp = spv::OpVectorTimesScalar;
3318 } else
3319 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321 case glslang::EOpVectorTimesMatrix:
3322 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003323 binOp = spv::OpVectorTimesMatrix;
3324 break;
3325 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003326 binOp = spv::OpMatrixTimesVector;
3327 break;
3328 case glslang::EOpMatrixTimesScalar:
3329 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003330 binOp = spv::OpMatrixTimesScalar;
3331 break;
3332 case glslang::EOpMatrixTimesMatrix:
3333 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003334 binOp = spv::OpMatrixTimesMatrix;
3335 break;
3336 case glslang::EOpOuterProduct:
3337 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003338 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003339 break;
3340
3341 case glslang::EOpDiv:
3342 case glslang::EOpDivAssign:
3343 if (isFloat)
3344 binOp = spv::OpFDiv;
3345 else if (isUnsigned)
3346 binOp = spv::OpUDiv;
3347 else
3348 binOp = spv::OpSDiv;
3349 break;
3350 case glslang::EOpMod:
3351 case glslang::EOpModAssign:
3352 if (isFloat)
3353 binOp = spv::OpFMod;
3354 else if (isUnsigned)
3355 binOp = spv::OpUMod;
3356 else
3357 binOp = spv::OpSMod;
3358 break;
3359 case glslang::EOpRightShift:
3360 case glslang::EOpRightShiftAssign:
3361 if (isUnsigned)
3362 binOp = spv::OpShiftRightLogical;
3363 else
3364 binOp = spv::OpShiftRightArithmetic;
3365 break;
3366 case glslang::EOpLeftShift:
3367 case glslang::EOpLeftShiftAssign:
3368 binOp = spv::OpShiftLeftLogical;
3369 break;
3370 case glslang::EOpAnd:
3371 case glslang::EOpAndAssign:
3372 binOp = spv::OpBitwiseAnd;
3373 break;
3374 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003375 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003376 binOp = spv::OpLogicalAnd;
3377 break;
3378 case glslang::EOpInclusiveOr:
3379 case glslang::EOpInclusiveOrAssign:
3380 binOp = spv::OpBitwiseOr;
3381 break;
3382 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003383 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003384 binOp = spv::OpLogicalOr;
3385 break;
3386 case glslang::EOpExclusiveOr:
3387 case glslang::EOpExclusiveOrAssign:
3388 binOp = spv::OpBitwiseXor;
3389 break;
3390 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003391 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003392 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003393 break;
3394
3395 case glslang::EOpLessThan:
3396 case glslang::EOpGreaterThan:
3397 case glslang::EOpLessThanEqual:
3398 case glslang::EOpGreaterThanEqual:
3399 case glslang::EOpEqual:
3400 case glslang::EOpNotEqual:
3401 case glslang::EOpVectorEqual:
3402 case glslang::EOpVectorNotEqual:
3403 comparison = true;
3404 break;
3405 default:
3406 break;
3407 }
3408
John Kessenich7c1aa102015-10-15 13:29:11 -06003409 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003410 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003411 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003412 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003413 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003414
3415 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003416 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003417 builder.promoteScalar(precision, left, right);
3418
qining25262b32016-05-06 17:25:16 -04003419 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3420 addDecoration(result, noContraction);
3421 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003422 }
3423
3424 if (! comparison)
3425 return 0;
3426
John Kessenich7c1aa102015-10-15 13:29:11 -06003427 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003428
John Kessenich4583b612016-08-07 19:14:22 -06003429 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3430 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003431 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003432
3433 switch (op) {
3434 case glslang::EOpLessThan:
3435 if (isFloat)
3436 binOp = spv::OpFOrdLessThan;
3437 else if (isUnsigned)
3438 binOp = spv::OpULessThan;
3439 else
3440 binOp = spv::OpSLessThan;
3441 break;
3442 case glslang::EOpGreaterThan:
3443 if (isFloat)
3444 binOp = spv::OpFOrdGreaterThan;
3445 else if (isUnsigned)
3446 binOp = spv::OpUGreaterThan;
3447 else
3448 binOp = spv::OpSGreaterThan;
3449 break;
3450 case glslang::EOpLessThanEqual:
3451 if (isFloat)
3452 binOp = spv::OpFOrdLessThanEqual;
3453 else if (isUnsigned)
3454 binOp = spv::OpULessThanEqual;
3455 else
3456 binOp = spv::OpSLessThanEqual;
3457 break;
3458 case glslang::EOpGreaterThanEqual:
3459 if (isFloat)
3460 binOp = spv::OpFOrdGreaterThanEqual;
3461 else if (isUnsigned)
3462 binOp = spv::OpUGreaterThanEqual;
3463 else
3464 binOp = spv::OpSGreaterThanEqual;
3465 break;
3466 case glslang::EOpEqual:
3467 case glslang::EOpVectorEqual:
3468 if (isFloat)
3469 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003470 else if (isBool)
3471 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003472 else
3473 binOp = spv::OpIEqual;
3474 break;
3475 case glslang::EOpNotEqual:
3476 case glslang::EOpVectorNotEqual:
3477 if (isFloat)
3478 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003479 else if (isBool)
3480 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003481 else
3482 binOp = spv::OpINotEqual;
3483 break;
3484 default:
3485 break;
3486 }
3487
qining25262b32016-05-06 17:25:16 -04003488 if (binOp != spv::OpNop) {
3489 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3490 addDecoration(result, noContraction);
3491 return builder.setPrecision(result, precision);
3492 }
John Kessenich140f3df2015-06-26 16:58:36 -06003493
3494 return 0;
3495}
3496
John Kessenich04bb8a02015-12-12 12:28:14 -07003497//
3498// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3499// These can be any of:
3500//
3501// matrix * scalar
3502// scalar * matrix
3503// matrix * matrix linear algebraic
3504// matrix * vector
3505// vector * matrix
3506// matrix * matrix componentwise
3507// matrix op matrix op in {+, -, /}
3508// matrix op scalar op in {+, -, /}
3509// scalar op matrix op in {+, -, /}
3510//
qining25262b32016-05-06 17:25:16 -04003511spv::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 -07003512{
3513 bool firstClass = true;
3514
3515 // First, handle first-class matrix operations (* and matrix/scalar)
3516 switch (op) {
3517 case spv::OpFDiv:
3518 if (builder.isMatrix(left) && builder.isScalar(right)) {
3519 // turn matrix / scalar into a multiply...
3520 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3521 op = spv::OpMatrixTimesScalar;
3522 } else
3523 firstClass = false;
3524 break;
3525 case spv::OpMatrixTimesScalar:
3526 if (builder.isMatrix(right))
3527 std::swap(left, right);
3528 assert(builder.isScalar(right));
3529 break;
3530 case spv::OpVectorTimesMatrix:
3531 assert(builder.isVector(left));
3532 assert(builder.isMatrix(right));
3533 break;
3534 case spv::OpMatrixTimesVector:
3535 assert(builder.isMatrix(left));
3536 assert(builder.isVector(right));
3537 break;
3538 case spv::OpMatrixTimesMatrix:
3539 assert(builder.isMatrix(left));
3540 assert(builder.isMatrix(right));
3541 break;
3542 default:
3543 firstClass = false;
3544 break;
3545 }
3546
qining25262b32016-05-06 17:25:16 -04003547 if (firstClass) {
3548 spv::Id result = builder.createBinOp(op, typeId, left, right);
3549 addDecoration(result, noContraction);
3550 return builder.setPrecision(result, precision);
3551 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003552
LoopDawg592860c2016-06-09 08:57:35 -06003553 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003554 // The result type of all of them is the same type as the (a) matrix operand.
3555 // The algorithm is to:
3556 // - break the matrix(es) into vectors
3557 // - smear any scalar to a vector
3558 // - do vector operations
3559 // - make a matrix out the vector results
3560 switch (op) {
3561 case spv::OpFAdd:
3562 case spv::OpFSub:
3563 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003564 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003565 case spv::OpFMul:
3566 {
3567 // one time set up...
3568 bool leftMat = builder.isMatrix(left);
3569 bool rightMat = builder.isMatrix(right);
3570 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3571 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3572 spv::Id scalarType = builder.getScalarTypeId(typeId);
3573 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3574 std::vector<spv::Id> results;
3575 spv::Id smearVec = spv::NoResult;
3576 if (builder.isScalar(left))
3577 smearVec = builder.smearScalar(precision, left, vecType);
3578 else if (builder.isScalar(right))
3579 smearVec = builder.smearScalar(precision, right, vecType);
3580
3581 // do each vector op
3582 for (unsigned int c = 0; c < numCols; ++c) {
3583 std::vector<unsigned int> indexes;
3584 indexes.push_back(c);
3585 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3586 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003587 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3588 addDecoration(result, noContraction);
3589 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003590 }
3591
3592 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003593 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003594 }
3595 default:
3596 assert(0);
3597 return spv::NoResult;
3598 }
3599}
3600
qining25262b32016-05-06 17:25:16 -04003601spv::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 -06003602{
3603 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003604 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003606 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003607#ifdef AMD_EXTENSIONS
3608 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3609#else
Rex Xu04db3f52015-09-16 11:44:02 +08003610 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003611#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003612
3613 switch (op) {
3614 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003615 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003616 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003617 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003618 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003619 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003620 unaryOp = spv::OpSNegate;
3621 break;
3622
3623 case glslang::EOpLogicalNot:
3624 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003625 unaryOp = spv::OpLogicalNot;
3626 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003627 case glslang::EOpBitwiseNot:
3628 unaryOp = spv::OpNot;
3629 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003630
John Kessenich140f3df2015-06-26 16:58:36 -06003631 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003632 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 break;
3634 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003636 break;
3637 case glslang::EOpTranspose:
3638 unaryOp = spv::OpTranspose;
3639 break;
3640
3641 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
3644 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003645 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003646 break;
3647 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003648 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003649 break;
3650 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003651 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003652 break;
3653 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003654 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
3656 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003657 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 break;
3659 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003661 break;
3662 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003663 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003664 break;
3665
3666 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003667 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003668 break;
3669 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003670 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003671 break;
3672 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003674 break;
3675 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003677 break;
3678 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003679 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003682 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003683 break;
3684
3685 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003686 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003689 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003690 break;
3691
3692 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710
3711 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 break;
3726 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003727 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729
3730 case glslang::EOpIsNan:
3731 unaryOp = spv::OpIsNan;
3732 break;
3733 case glslang::EOpIsInf:
3734 unaryOp = spv::OpIsInf;
3735 break;
LoopDawg592860c2016-06-09 08:57:35 -06003736 case glslang::EOpIsFinite:
3737 unaryOp = spv::OpIsFinite;
3738 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003739
Rex Xucbc426e2015-12-15 16:03:10 +08003740 case glslang::EOpFloatBitsToInt:
3741 case glslang::EOpFloatBitsToUint:
3742 case glslang::EOpIntBitsToFloat:
3743 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003744 case glslang::EOpDoubleBitsToInt64:
3745 case glslang::EOpDoubleBitsToUint64:
3746 case glslang::EOpInt64BitsToDouble:
3747 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003748 unaryOp = spv::OpBitcast;
3749 break;
3750
John Kessenich140f3df2015-06-26 16:58:36 -06003751 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003752 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003769 case glslang::EOpPackSnorm4x8:
3770 libCall = spv::GLSLstd450PackSnorm4x8;
3771 break;
3772 case glslang::EOpUnpackSnorm4x8:
3773 libCall = spv::GLSLstd450UnpackSnorm4x8;
3774 break;
3775 case glslang::EOpPackUnorm4x8:
3776 libCall = spv::GLSLstd450PackUnorm4x8;
3777 break;
3778 case glslang::EOpUnpackUnorm4x8:
3779 libCall = spv::GLSLstd450UnpackUnorm4x8;
3780 break;
3781 case glslang::EOpPackDouble2x32:
3782 libCall = spv::GLSLstd450PackDouble2x32;
3783 break;
3784 case glslang::EOpUnpackDouble2x32:
3785 libCall = spv::GLSLstd450UnpackDouble2x32;
3786 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003787
Rex Xu8ff43de2016-04-22 16:51:45 +08003788 case glslang::EOpPackInt2x32:
3789 case glslang::EOpUnpackInt2x32:
3790 case glslang::EOpPackUint2x32:
3791 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003792 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003793 break;
3794
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003795#ifdef AMD_EXTENSIONS
3796 case glslang::EOpPackFloat2x16:
3797 case glslang::EOpUnpackFloat2x16:
3798 unaryOp = spv::OpBitcast;
3799 break;
3800#endif
3801
John Kessenich140f3df2015-06-26 16:58:36 -06003802 case glslang::EOpDPdx:
3803 unaryOp = spv::OpDPdx;
3804 break;
3805 case glslang::EOpDPdy:
3806 unaryOp = spv::OpDPdy;
3807 break;
3808 case glslang::EOpFwidth:
3809 unaryOp = spv::OpFwidth;
3810 break;
3811 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003812 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003813 unaryOp = spv::OpDPdxFine;
3814 break;
3815 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003816 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003817 unaryOp = spv::OpDPdyFine;
3818 break;
3819 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003820 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003821 unaryOp = spv::OpFwidthFine;
3822 break;
3823 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003824 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003825 unaryOp = spv::OpDPdxCoarse;
3826 break;
3827 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003828 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 unaryOp = spv::OpDPdyCoarse;
3830 break;
3831 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003832 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003833 unaryOp = spv::OpFwidthCoarse;
3834 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003835 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003836 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003837 libCall = spv::GLSLstd450InterpolateAtCentroid;
3838 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003839 case glslang::EOpAny:
3840 unaryOp = spv::OpAny;
3841 break;
3842 case glslang::EOpAll:
3843 unaryOp = spv::OpAll;
3844 break;
3845
3846 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 if (isFloat)
3848 libCall = spv::GLSLstd450FAbs;
3849 else
3850 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003851 break;
3852 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003853 if (isFloat)
3854 libCall = spv::GLSLstd450FSign;
3855 else
3856 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003857 break;
3858
John Kessenichfc51d282015-08-19 13:34:18 -06003859 case glslang::EOpAtomicCounterIncrement:
3860 case glslang::EOpAtomicCounterDecrement:
3861 case glslang::EOpAtomicCounter:
3862 {
3863 // Handle all of the atomics in one place, in createAtomicOperation()
3864 std::vector<spv::Id> operands;
3865 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003866 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003867 }
3868
John Kessenichfc51d282015-08-19 13:34:18 -06003869 case glslang::EOpBitFieldReverse:
3870 unaryOp = spv::OpBitReverse;
3871 break;
3872 case glslang::EOpBitCount:
3873 unaryOp = spv::OpBitCount;
3874 break;
3875 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003876 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003877 break;
3878 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003879 if (isUnsigned)
3880 libCall = spv::GLSLstd450FindUMsb;
3881 else
3882 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003883 break;
3884
Rex Xu574ab042016-04-14 16:53:07 +08003885 case glslang::EOpBallot:
3886 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003887 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003888 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003889 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003890#ifdef AMD_EXTENSIONS
3891 case glslang::EOpMinInvocations:
3892 case glslang::EOpMaxInvocations:
3893 case glslang::EOpAddInvocations:
3894 case glslang::EOpMinInvocationsNonUniform:
3895 case glslang::EOpMaxInvocationsNonUniform:
3896 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003897 case glslang::EOpMinInvocationsInclusiveScan:
3898 case glslang::EOpMaxInvocationsInclusiveScan:
3899 case glslang::EOpAddInvocationsInclusiveScan:
3900 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3901 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3902 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3903 case glslang::EOpMinInvocationsExclusiveScan:
3904 case glslang::EOpMaxInvocationsExclusiveScan:
3905 case glslang::EOpAddInvocationsExclusiveScan:
3906 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3907 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3908 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003909#endif
Rex Xu51596642016-09-21 18:56:12 +08003910 {
3911 std::vector<spv::Id> operands;
3912 operands.push_back(operand);
3913 return createInvocationsOperation(op, typeId, operands, typeProxy);
3914 }
Rex Xu9d93a232016-05-05 12:30:44 +08003915
3916#ifdef AMD_EXTENSIONS
3917 case glslang::EOpMbcnt:
3918 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3919 libCall = spv::MbcntAMD;
3920 break;
3921
3922 case glslang::EOpCubeFaceIndex:
3923 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3924 libCall = spv::CubeFaceIndexAMD;
3925 break;
3926
3927 case glslang::EOpCubeFaceCoord:
3928 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3929 libCall = spv::CubeFaceCoordAMD;
3930 break;
3931#endif
Rex Xu338b1852016-05-05 20:38:33 +08003932
John Kessenich140f3df2015-06-26 16:58:36 -06003933 default:
3934 return 0;
3935 }
3936
3937 spv::Id id;
3938 if (libCall >= 0) {
3939 std::vector<spv::Id> args;
3940 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003941 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003942 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003943 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003944 }
John Kessenich140f3df2015-06-26 16:58:36 -06003945
qining25262b32016-05-06 17:25:16 -04003946 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003947 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003948}
3949
John Kessenich7a53f762016-01-20 11:19:27 -07003950// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003951spv::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 -07003952{
3953 // Handle unary operations vector by vector.
3954 // The result type is the same type as the original type.
3955 // The algorithm is to:
3956 // - break the matrix into vectors
3957 // - apply the operation to each vector
3958 // - make a matrix out the vector results
3959
3960 // get the types sorted out
3961 int numCols = builder.getNumColumns(operand);
3962 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003963 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3964 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003965 std::vector<spv::Id> results;
3966
3967 // do each vector op
3968 for (int c = 0; c < numCols; ++c) {
3969 std::vector<unsigned int> indexes;
3970 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003971 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3972 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3973 addDecoration(destVec, noContraction);
3974 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003975 }
3976
3977 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003978 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003979}
3980
Rex Xu73e3ce72016-04-27 18:48:17 +08003981spv::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 -06003982{
3983 spv::Op convOp = spv::OpNop;
3984 spv::Id zero = 0;
3985 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003986 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003987
3988 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3989
3990 switch (op) {
3991 case glslang::EOpConvIntToBool:
3992 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003993 case glslang::EOpConvInt64ToBool:
3994 case glslang::EOpConvUint64ToBool:
3995 zero = (op == glslang::EOpConvInt64ToBool ||
3996 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003997 zero = makeSmearedConstant(zero, vectorSize);
3998 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3999
4000 case glslang::EOpConvFloatToBool:
4001 zero = builder.makeFloatConstant(0.0F);
4002 zero = makeSmearedConstant(zero, vectorSize);
4003 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4004
4005 case glslang::EOpConvDoubleToBool:
4006 zero = builder.makeDoubleConstant(0.0);
4007 zero = makeSmearedConstant(zero, vectorSize);
4008 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4009
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004010#ifdef AMD_EXTENSIONS
4011 case glslang::EOpConvFloat16ToBool:
4012 zero = builder.makeFloat16Constant(0.0F);
4013 zero = makeSmearedConstant(zero, vectorSize);
4014 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4015#endif
4016
John Kessenich140f3df2015-06-26 16:58:36 -06004017 case glslang::EOpConvBoolToFloat:
4018 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004019 zero = builder.makeFloatConstant(0.0F);
4020 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004021 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004022
John Kessenich140f3df2015-06-26 16:58:36 -06004023 case glslang::EOpConvBoolToDouble:
4024 convOp = spv::OpSelect;
4025 zero = builder.makeDoubleConstant(0.0);
4026 one = builder.makeDoubleConstant(1.0);
4027 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004028
4029#ifdef AMD_EXTENSIONS
4030 case glslang::EOpConvBoolToFloat16:
4031 convOp = spv::OpSelect;
4032 zero = builder.makeFloat16Constant(0.0F);
4033 one = builder.makeFloat16Constant(1.0F);
4034 break;
4035#endif
4036
John Kessenich140f3df2015-06-26 16:58:36 -06004037 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004038 case glslang::EOpConvBoolToInt64:
4039 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4040 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004041 convOp = spv::OpSelect;
4042 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004043
John Kessenich140f3df2015-06-26 16:58:36 -06004044 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004045 case glslang::EOpConvBoolToUint64:
4046 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4047 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004048 convOp = spv::OpSelect;
4049 break;
4050
4051 case glslang::EOpConvIntToFloat:
4052 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004053 case glslang::EOpConvInt64ToFloat:
4054 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004055#ifdef AMD_EXTENSIONS
4056 case glslang::EOpConvIntToFloat16:
4057 case glslang::EOpConvInt64ToFloat16:
4058#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004059 convOp = spv::OpConvertSToF;
4060 break;
4061
4062 case glslang::EOpConvUintToFloat:
4063 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004064 case glslang::EOpConvUint64ToFloat:
4065 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004066#ifdef AMD_EXTENSIONS
4067 case glslang::EOpConvUintToFloat16:
4068 case glslang::EOpConvUint64ToFloat16:
4069#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004070 convOp = spv::OpConvertUToF;
4071 break;
4072
4073 case glslang::EOpConvDoubleToFloat:
4074 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004075#ifdef AMD_EXTENSIONS
4076 case glslang::EOpConvDoubleToFloat16:
4077 case glslang::EOpConvFloat16ToDouble:
4078 case glslang::EOpConvFloatToFloat16:
4079 case glslang::EOpConvFloat16ToFloat:
4080#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004081 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004082 if (builder.isMatrixType(destType))
4083 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004084 break;
4085
4086 case glslang::EOpConvFloatToInt:
4087 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004088 case glslang::EOpConvFloatToInt64:
4089 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004090#ifdef AMD_EXTENSIONS
4091 case glslang::EOpConvFloat16ToInt:
4092 case glslang::EOpConvFloat16ToInt64:
4093#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004094 convOp = spv::OpConvertFToS;
4095 break;
4096
4097 case glslang::EOpConvUintToInt:
4098 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004099 case glslang::EOpConvUint64ToInt64:
4100 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004101 if (builder.isInSpecConstCodeGenMode()) {
4102 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004103 zero = (op == glslang::EOpConvUint64ToInt64 ||
4104 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004105 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004106 // Use OpIAdd, instead of OpBitcast to do the conversion when
4107 // generating for OpSpecConstantOp instruction.
4108 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4109 }
4110 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004111 convOp = spv::OpBitcast;
4112 break;
4113
4114 case glslang::EOpConvFloatToUint:
4115 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004116 case glslang::EOpConvFloatToUint64:
4117 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004118#ifdef AMD_EXTENSIONS
4119 case glslang::EOpConvFloat16ToUint:
4120 case glslang::EOpConvFloat16ToUint64:
4121#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004122 convOp = spv::OpConvertFToU;
4123 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004124
4125 case glslang::EOpConvIntToInt64:
4126 case glslang::EOpConvInt64ToInt:
4127 convOp = spv::OpSConvert;
4128 break;
4129
4130 case glslang::EOpConvUintToUint64:
4131 case glslang::EOpConvUint64ToUint:
4132 convOp = spv::OpUConvert;
4133 break;
4134
4135 case glslang::EOpConvIntToUint64:
4136 case glslang::EOpConvInt64ToUint:
4137 case glslang::EOpConvUint64ToInt:
4138 case glslang::EOpConvUintToInt64:
4139 // OpSConvert/OpUConvert + OpBitCast
4140 switch (op) {
4141 case glslang::EOpConvIntToUint64:
4142 convOp = spv::OpSConvert;
4143 type = builder.makeIntType(64);
4144 break;
4145 case glslang::EOpConvInt64ToUint:
4146 convOp = spv::OpSConvert;
4147 type = builder.makeIntType(32);
4148 break;
4149 case glslang::EOpConvUint64ToInt:
4150 convOp = spv::OpUConvert;
4151 type = builder.makeUintType(32);
4152 break;
4153 case glslang::EOpConvUintToInt64:
4154 convOp = spv::OpUConvert;
4155 type = builder.makeUintType(64);
4156 break;
4157 default:
4158 assert(0);
4159 break;
4160 }
4161
4162 if (vectorSize > 0)
4163 type = builder.makeVectorType(type, vectorSize);
4164
4165 operand = builder.createUnaryOp(convOp, type, operand);
4166
4167 if (builder.isInSpecConstCodeGenMode()) {
4168 // Build zero scalar or vector for OpIAdd.
4169 zero = (op == glslang::EOpConvIntToUint64 ||
4170 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4171 zero = makeSmearedConstant(zero, vectorSize);
4172 // Use OpIAdd, instead of OpBitcast to do the conversion when
4173 // generating for OpSpecConstantOp instruction.
4174 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4175 }
4176 // For normal run-time conversion instruction, use OpBitcast.
4177 convOp = spv::OpBitcast;
4178 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 default:
4180 break;
4181 }
4182
4183 spv::Id result = 0;
4184 if (convOp == spv::OpNop)
4185 return result;
4186
4187 if (convOp == spv::OpSelect) {
4188 zero = makeSmearedConstant(zero, vectorSize);
4189 one = makeSmearedConstant(one, vectorSize);
4190 result = builder.createTriOp(convOp, destType, operand, one, zero);
4191 } else
4192 result = builder.createUnaryOp(convOp, destType, operand);
4193
John Kessenich32cfd492016-02-02 12:37:46 -07004194 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004195}
4196
4197spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4198{
4199 if (vectorSize == 0)
4200 return constant;
4201
4202 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4203 std::vector<spv::Id> components;
4204 for (int c = 0; c < vectorSize; ++c)
4205 components.push_back(constant);
4206 return builder.makeCompositeConstant(vectorTypeId, components);
4207}
4208
John Kessenich426394d2015-07-23 10:22:48 -06004209// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004210spv::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 -06004211{
4212 spv::Op opCode = spv::OpNop;
4213
4214 switch (op) {
4215 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004216 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004217 opCode = spv::OpAtomicIAdd;
4218 break;
4219 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004220 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004221 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004222 break;
4223 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004224 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004225 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004226 break;
4227 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004228 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004229 opCode = spv::OpAtomicAnd;
4230 break;
4231 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004232 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004233 opCode = spv::OpAtomicOr;
4234 break;
4235 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004236 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004237 opCode = spv::OpAtomicXor;
4238 break;
4239 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004240 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004241 opCode = spv::OpAtomicExchange;
4242 break;
4243 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004244 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004245 opCode = spv::OpAtomicCompareExchange;
4246 break;
4247 case glslang::EOpAtomicCounterIncrement:
4248 opCode = spv::OpAtomicIIncrement;
4249 break;
4250 case glslang::EOpAtomicCounterDecrement:
4251 opCode = spv::OpAtomicIDecrement;
4252 break;
4253 case glslang::EOpAtomicCounter:
4254 opCode = spv::OpAtomicLoad;
4255 break;
4256 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004257 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004258 break;
4259 }
4260
4261 // Sort out the operands
4262 // - mapping from glslang -> SPV
4263 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004264 // - compare-exchange swaps the value and comparator
4265 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004266 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4267 auto opIt = operands.begin(); // walk the glslang operands
4268 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004269 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4270 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4271 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004272 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4273 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004274 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004275 spvAtomicOperands.push_back(*(opIt + 1));
4276 spvAtomicOperands.push_back(*opIt);
4277 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004278 }
John Kessenich426394d2015-07-23 10:22:48 -06004279
John Kessenich3e60a6f2015-09-14 22:45:16 -06004280 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004281 for (; opIt != operands.end(); ++opIt)
4282 spvAtomicOperands.push_back(*opIt);
4283
4284 return builder.createOp(opCode, typeId, spvAtomicOperands);
4285}
4286
John Kessenich91cef522016-05-05 16:45:40 -06004287// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004288spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004289{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004290#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004291 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004292 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004293#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004294
Rex Xu51596642016-09-21 18:56:12 +08004295 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004296 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004297 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4298
chaocf200da82016-12-20 12:44:35 -08004299 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4300 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004301 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4302 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004303 } else if (op == glslang::EOpAnyInvocation ||
4304 op == glslang::EOpAllInvocations ||
4305 op == glslang::EOpAllInvocationsEqual) {
4306 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4307 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004308 } else {
4309 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004310#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004311 if (op == glslang::EOpMinInvocationsNonUniform ||
4312 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004313 op == glslang::EOpAddInvocationsNonUniform ||
4314 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4315 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4316 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4317 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4318 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4319 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004320 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004321#endif
Rex Xu51596642016-09-21 18:56:12 +08004322
4323 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004324#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004325 switch (op) {
4326 case glslang::EOpMinInvocations:
4327 case glslang::EOpMaxInvocations:
4328 case glslang::EOpAddInvocations:
4329 case glslang::EOpMinInvocationsNonUniform:
4330 case glslang::EOpMaxInvocationsNonUniform:
4331 case glslang::EOpAddInvocationsNonUniform:
4332 groupOperation = spv::GroupOperationReduce;
4333 spvGroupOperands.push_back(groupOperation);
4334 break;
4335 case glslang::EOpMinInvocationsInclusiveScan:
4336 case glslang::EOpMaxInvocationsInclusiveScan:
4337 case glslang::EOpAddInvocationsInclusiveScan:
4338 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4339 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4340 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4341 groupOperation = spv::GroupOperationInclusiveScan;
4342 spvGroupOperands.push_back(groupOperation);
4343 break;
4344 case glslang::EOpMinInvocationsExclusiveScan:
4345 case glslang::EOpMaxInvocationsExclusiveScan:
4346 case glslang::EOpAddInvocationsExclusiveScan:
4347 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4348 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4349 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4350 groupOperation = spv::GroupOperationExclusiveScan;
4351 spvGroupOperands.push_back(groupOperation);
4352 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004353 default:
4354 break;
Rex Xu430ef402016-10-14 17:22:23 +08004355 }
Rex Xu9d93a232016-05-05 12:30:44 +08004356#endif
Rex Xu51596642016-09-21 18:56:12 +08004357 }
4358
4359 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4360 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004361
4362 switch (op) {
4363 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004364 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004365 break;
John Kessenich91cef522016-05-05 16:45:40 -06004366 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004367 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004368 break;
John Kessenich91cef522016-05-05 16:45:40 -06004369 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004370 opCode = spv::OpSubgroupAllEqualKHR;
4371 break;
Rex Xu51596642016-09-21 18:56:12 +08004372 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004373 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004374 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004375 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004376 break;
4377 case glslang::EOpReadFirstInvocation:
4378 opCode = spv::OpSubgroupFirstInvocationKHR;
4379 break;
4380 case glslang::EOpBallot:
4381 {
4382 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4383 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4384 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4385 //
4386 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4387 //
4388 spv::Id uintType = builder.makeUintType(32);
4389 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4390 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4391
4392 std::vector<spv::Id> components;
4393 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4394 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4395
4396 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4397 return builder.createUnaryOp(spv::OpBitcast, typeId,
4398 builder.createCompositeConstruct(uvec2Type, components));
4399 }
4400
Rex Xu9d93a232016-05-05 12:30:44 +08004401#ifdef AMD_EXTENSIONS
4402 case glslang::EOpMinInvocations:
4403 case glslang::EOpMaxInvocations:
4404 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004405 case glslang::EOpMinInvocationsInclusiveScan:
4406 case glslang::EOpMaxInvocationsInclusiveScan:
4407 case glslang::EOpAddInvocationsInclusiveScan:
4408 case glslang::EOpMinInvocationsExclusiveScan:
4409 case glslang::EOpMaxInvocationsExclusiveScan:
4410 case glslang::EOpAddInvocationsExclusiveScan:
4411 if (op == glslang::EOpMinInvocations ||
4412 op == glslang::EOpMinInvocationsInclusiveScan ||
4413 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004414 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004415 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004416 else {
4417 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004418 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004419 else
Rex Xu51596642016-09-21 18:56:12 +08004420 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004421 }
Rex Xu430ef402016-10-14 17:22:23 +08004422 } else if (op == glslang::EOpMaxInvocations ||
4423 op == glslang::EOpMaxInvocationsInclusiveScan ||
4424 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004425 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004426 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004427 else {
4428 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004429 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004430 else
Rex Xu51596642016-09-21 18:56:12 +08004431 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004432 }
4433 } else {
4434 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004435 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004436 else
Rex Xu51596642016-09-21 18:56:12 +08004437 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004438 }
4439
Rex Xu2bbbe062016-08-23 15:41:05 +08004440 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004441 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004442
4443 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004444 case glslang::EOpMinInvocationsNonUniform:
4445 case glslang::EOpMaxInvocationsNonUniform:
4446 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004447 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4448 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4449 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4450 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4451 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4452 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4453 if (op == glslang::EOpMinInvocationsNonUniform ||
4454 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4455 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004456 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004457 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004458 else {
4459 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004460 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004461 else
Rex Xu51596642016-09-21 18:56:12 +08004462 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004463 }
4464 }
Rex Xu430ef402016-10-14 17:22:23 +08004465 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4466 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4467 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004468 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004469 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004470 else {
4471 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004472 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004473 else
Rex Xu51596642016-09-21 18:56:12 +08004474 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004475 }
4476 }
4477 else {
4478 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004479 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004480 else
Rex Xu51596642016-09-21 18:56:12 +08004481 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004482 }
4483
Rex Xu2bbbe062016-08-23 15:41:05 +08004484 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004485 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004486
4487 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004488#endif
John Kessenich91cef522016-05-05 16:45:40 -06004489 default:
4490 logger->missingFunctionality("invocation operation");
4491 return spv::NoResult;
4492 }
Rex Xu51596642016-09-21 18:56:12 +08004493
4494 assert(opCode != spv::OpNop);
4495 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004496}
4497
Rex Xu2bbbe062016-08-23 15:41:05 +08004498// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004499spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004500{
Rex Xub7072052016-09-26 15:53:40 +08004501#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004502 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4503 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004504 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004505 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004506 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4507 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4508 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004509#else
4510 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4511 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004512 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4513 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004514#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004515
4516 // Handle group invocation operations scalar by scalar.
4517 // The result type is the same type as the original type.
4518 // The algorithm is to:
4519 // - break the vector into scalars
4520 // - apply the operation to each scalar
4521 // - make a vector out the scalar results
4522
4523 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004524 int numComponents = builder.getNumComponents(operands[0]);
4525 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004526 std::vector<spv::Id> results;
4527
4528 // do each scalar op
4529 for (int comp = 0; comp < numComponents; ++comp) {
4530 std::vector<unsigned int> indexes;
4531 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004532 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004533 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004534 if (op == spv::OpSubgroupReadInvocationKHR) {
4535 spvGroupOperands.push_back(scalar);
4536 spvGroupOperands.push_back(operands[1]);
4537 } else if (op == spv::OpGroupBroadcast) {
4538 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004539 spvGroupOperands.push_back(scalar);
4540 spvGroupOperands.push_back(operands[1]);
4541 } else {
chaocf200da82016-12-20 12:44:35 -08004542 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004543 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004544 spvGroupOperands.push_back(scalar);
4545 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004546
Rex Xub7072052016-09-26 15:53:40 +08004547 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004548 }
4549
4550 // put the pieces together
4551 return builder.createCompositeConstruct(typeId, results);
4552}
Rex Xu2bbbe062016-08-23 15:41:05 +08004553
John Kessenich5e4b1242015-08-06 22:53:06 -06004554spv::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 -06004555{
Rex Xu8ff43de2016-04-22 16:51:45 +08004556 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004557#ifdef AMD_EXTENSIONS
4558 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4559#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004560 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004561#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004562
John Kessenich140f3df2015-06-26 16:58:36 -06004563 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004564 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004565 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004566 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004567 spv::Id typeId0 = 0;
4568 if (consumedOperands > 0)
4569 typeId0 = builder.getTypeId(operands[0]);
4570 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004571
4572 switch (op) {
4573 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004574 if (isFloat)
4575 libCall = spv::GLSLstd450FMin;
4576 else if (isUnsigned)
4577 libCall = spv::GLSLstd450UMin;
4578 else
4579 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004580 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004581 break;
4582 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004583 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004584 break;
4585 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004586 if (isFloat)
4587 libCall = spv::GLSLstd450FMax;
4588 else if (isUnsigned)
4589 libCall = spv::GLSLstd450UMax;
4590 else
4591 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004592 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004593 break;
4594 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004595 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004596 break;
4597 case glslang::EOpDot:
4598 opCode = spv::OpDot;
4599 break;
4600 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004601 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004602 break;
4603
4604 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004605 if (isFloat)
4606 libCall = spv::GLSLstd450FClamp;
4607 else if (isUnsigned)
4608 libCall = spv::GLSLstd450UClamp;
4609 else
4610 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004611 builder.promoteScalar(precision, operands.front(), operands[1]);
4612 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 break;
4614 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004615 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4616 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004617 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004618 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004619 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004620 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004621 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004622 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004623 break;
4624 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004625 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004626 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004627 break;
4628 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004629 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004630 builder.promoteScalar(precision, operands[0], operands[2]);
4631 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004632 break;
4633
4634 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004635 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004636 break;
4637 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004638 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004639 break;
4640 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004641 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004642 break;
4643 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004644 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004645 break;
4646 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004647 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004648 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004649 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004650 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004651 libCall = spv::GLSLstd450InterpolateAtSample;
4652 break;
4653 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004654 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004655 libCall = spv::GLSLstd450InterpolateAtOffset;
4656 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004657 case glslang::EOpAddCarry:
4658 opCode = spv::OpIAddCarry;
4659 typeId = builder.makeStructResultType(typeId0, typeId0);
4660 consumedOperands = 2;
4661 break;
4662 case glslang::EOpSubBorrow:
4663 opCode = spv::OpISubBorrow;
4664 typeId = builder.makeStructResultType(typeId0, typeId0);
4665 consumedOperands = 2;
4666 break;
4667 case glslang::EOpUMulExtended:
4668 opCode = spv::OpUMulExtended;
4669 typeId = builder.makeStructResultType(typeId0, typeId0);
4670 consumedOperands = 2;
4671 break;
4672 case glslang::EOpIMulExtended:
4673 opCode = spv::OpSMulExtended;
4674 typeId = builder.makeStructResultType(typeId0, typeId0);
4675 consumedOperands = 2;
4676 break;
4677 case glslang::EOpBitfieldExtract:
4678 if (isUnsigned)
4679 opCode = spv::OpBitFieldUExtract;
4680 else
4681 opCode = spv::OpBitFieldSExtract;
4682 break;
4683 case glslang::EOpBitfieldInsert:
4684 opCode = spv::OpBitFieldInsert;
4685 break;
4686
4687 case glslang::EOpFma:
4688 libCall = spv::GLSLstd450Fma;
4689 break;
4690 case glslang::EOpFrexp:
4691 libCall = spv::GLSLstd450FrexpStruct;
4692 if (builder.getNumComponents(operands[0]) == 1)
4693 frexpIntType = builder.makeIntegerType(32, true);
4694 else
4695 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4696 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4697 consumedOperands = 1;
4698 break;
4699 case glslang::EOpLdexp:
4700 libCall = spv::GLSLstd450Ldexp;
4701 break;
4702
Rex Xu574ab042016-04-14 16:53:07 +08004703 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004704 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004705
Rex Xu9d93a232016-05-05 12:30:44 +08004706#ifdef AMD_EXTENSIONS
4707 case glslang::EOpSwizzleInvocations:
4708 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4709 libCall = spv::SwizzleInvocationsAMD;
4710 break;
4711 case glslang::EOpSwizzleInvocationsMasked:
4712 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4713 libCall = spv::SwizzleInvocationsMaskedAMD;
4714 break;
4715 case glslang::EOpWriteInvocation:
4716 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4717 libCall = spv::WriteInvocationAMD;
4718 break;
4719
4720 case glslang::EOpMin3:
4721 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4722 if (isFloat)
4723 libCall = spv::FMin3AMD;
4724 else {
4725 if (isUnsigned)
4726 libCall = spv::UMin3AMD;
4727 else
4728 libCall = spv::SMin3AMD;
4729 }
4730 break;
4731 case glslang::EOpMax3:
4732 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4733 if (isFloat)
4734 libCall = spv::FMax3AMD;
4735 else {
4736 if (isUnsigned)
4737 libCall = spv::UMax3AMD;
4738 else
4739 libCall = spv::SMax3AMD;
4740 }
4741 break;
4742 case glslang::EOpMid3:
4743 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4744 if (isFloat)
4745 libCall = spv::FMid3AMD;
4746 else {
4747 if (isUnsigned)
4748 libCall = spv::UMid3AMD;
4749 else
4750 libCall = spv::SMid3AMD;
4751 }
4752 break;
4753
4754 case glslang::EOpInterpolateAtVertex:
4755 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4756 libCall = spv::InterpolateAtVertexAMD;
4757 break;
4758#endif
4759
John Kessenich140f3df2015-06-26 16:58:36 -06004760 default:
4761 return 0;
4762 }
4763
4764 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004765 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004766 // Use an extended instruction from the standard library.
4767 // Construct the call arguments, without modifying the original operands vector.
4768 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4769 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004770 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004771 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004772 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004773 case 0:
4774 // should all be handled by visitAggregate and createNoArgOperation
4775 assert(0);
4776 return 0;
4777 case 1:
4778 // should all be handled by createUnaryOperation
4779 assert(0);
4780 return 0;
4781 case 2:
4782 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4783 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004784 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004785 // anything 3 or over doesn't have l-value operands, so all should be consumed
4786 assert(consumedOperands == operands.size());
4787 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004788 break;
4789 }
4790 }
4791
John Kessenich55e7d112015-11-15 21:33:39 -07004792 // Decode the return types that were structures
4793 switch (op) {
4794 case glslang::EOpAddCarry:
4795 case glslang::EOpSubBorrow:
4796 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4797 id = builder.createCompositeExtract(id, typeId0, 0);
4798 break;
4799 case glslang::EOpUMulExtended:
4800 case glslang::EOpIMulExtended:
4801 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4802 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4803 break;
4804 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004805 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004806 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4807 id = builder.createCompositeExtract(id, typeId0, 0);
4808 break;
4809 default:
4810 break;
4811 }
4812
John Kessenich32cfd492016-02-02 12:37:46 -07004813 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004814}
4815
Rex Xu9d93a232016-05-05 12:30:44 +08004816// Intrinsics with no arguments (or no return value, and no precision).
4817spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004818{
4819 // TODO: get the barrier operands correct
4820
4821 switch (op) {
4822 case glslang::EOpEmitVertex:
4823 builder.createNoResultOp(spv::OpEmitVertex);
4824 return 0;
4825 case glslang::EOpEndPrimitive:
4826 builder.createNoResultOp(spv::OpEndPrimitive);
4827 return 0;
4828 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004829 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004830 return 0;
4831 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004832 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004833 return 0;
4834 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004835 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004836 return 0;
4837 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004838 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004839 return 0;
4840 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004841 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004842 return 0;
4843 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004844 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004845 return 0;
4846 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004847 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004848 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004849 case glslang::EOpAllMemoryBarrierWithGroupSync:
4850 // Control barrier with non-"None" semantic is also a memory barrier.
4851 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4852 return 0;
4853 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4854 // Control barrier with non-"None" semantic is also a memory barrier.
4855 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4856 return 0;
4857 case glslang::EOpWorkgroupMemoryBarrier:
4858 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4859 return 0;
4860 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4861 // Control barrier with non-"None" semantic is also a memory barrier.
4862 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4863 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004864#ifdef AMD_EXTENSIONS
4865 case glslang::EOpTime:
4866 {
4867 std::vector<spv::Id> args; // Dummy arguments
4868 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4869 return builder.setPrecision(id, precision);
4870 }
4871#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004872 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004873 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004874 return 0;
4875 }
4876}
4877
4878spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4879{
John Kessenich2f273362015-07-18 22:34:27 -06004880 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004881 spv::Id id;
4882 if (symbolValues.end() != iter) {
4883 id = iter->second;
4884 return id;
4885 }
4886
4887 // it was not found, create it
4888 id = createSpvVariable(symbol);
4889 symbolValues[symbol->getId()] = id;
4890
Rex Xuc884b4a2016-06-29 15:03:44 +08004891 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004892 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004893 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004894 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004895 if (symbol->getType().getQualifier().hasSpecConstantId())
4896 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004897 if (symbol->getQualifier().hasIndex())
4898 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4899 if (symbol->getQualifier().hasComponent())
4900 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4901 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004902 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004903 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004904 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004905 if (symbol->getQualifier().hasXfbBuffer())
4906 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4907 if (symbol->getQualifier().hasXfbOffset())
4908 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4909 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004910 // atomic counters use this:
4911 if (symbol->getQualifier().hasOffset())
4912 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004913 }
4914
scygan2c864272016-05-18 18:09:17 +02004915 if (symbol->getQualifier().hasLocation())
4916 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004917 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004918 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004919 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004920 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004921 }
John Kessenich140f3df2015-06-26 16:58:36 -06004922 if (symbol->getQualifier().hasSet())
4923 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004924 else if (IsDescriptorResource(symbol->getType())) {
4925 // default to 0
4926 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4927 }
John Kessenich140f3df2015-06-26 16:58:36 -06004928 if (symbol->getQualifier().hasBinding())
4929 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004930 if (symbol->getQualifier().hasAttachment())
4931 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004932 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004933 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004934 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004935 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004936 if (symbol->getQualifier().hasXfbBuffer())
4937 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4938 }
4939
Rex Xu1da878f2016-02-21 20:59:01 +08004940 if (symbol->getType().isImage()) {
4941 std::vector<spv::Decoration> memory;
4942 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4943 for (unsigned int i = 0; i < memory.size(); ++i)
4944 addDecoration(id, memory[i]);
4945 }
4946
John Kessenich140f3df2015-06-26 16:58:36 -06004947 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004948 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004949 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004950 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004951
John Kessenichecba76f2017-01-06 00:34:48 -07004952#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004953 if (builtIn == spv::BuiltInSampleMask) {
4954 spv::Decoration decoration;
4955 // GL_NV_sample_mask_override_coverage extension
4956 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004957 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004958 else
4959 decoration = (spv::Decoration)spv::DecorationMax;
4960 addDecoration(id, decoration);
4961 if (decoration != spv::DecorationMax) {
4962 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4963 }
4964 }
chaoc771d89f2017-01-13 01:10:53 -08004965 else if (builtIn == spv::BuiltInLayer) {
4966 // SPV_NV_viewport_array2 extension
4967 if (symbol->getQualifier().layoutViewportRelative)
4968 {
4969 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4970 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4971 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4972 }
4973 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4974 {
4975 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4976 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4977 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4978 }
4979 }
4980
chaoc6e5acae2016-12-20 13:28:52 -08004981 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004982 addDecoration(id, spv::DecorationPassthroughNV);
4983 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004984 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4985 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004986#endif
4987
John Kessenich140f3df2015-06-26 16:58:36 -06004988 return id;
4989}
4990
John Kessenich55e7d112015-11-15 21:33:39 -07004991// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004992void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4993{
John Kessenich4016e382016-07-15 11:53:56 -06004994 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004995 builder.addDecoration(id, dec);
4996}
4997
John Kessenich55e7d112015-11-15 21:33:39 -07004998// If 'dec' is valid, add a one-operand decoration to an object
4999void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5000{
John Kessenich4016e382016-07-15 11:53:56 -06005001 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005002 builder.addDecoration(id, dec, value);
5003}
5004
5005// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005006void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5007{
John Kessenich4016e382016-07-15 11:53:56 -06005008 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005009 builder.addMemberDecoration(id, (unsigned)member, dec);
5010}
5011
John Kessenich92187592016-02-01 13:45:25 -07005012// If 'dec' is valid, add a one-operand decoration to a struct member
5013void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5014{
John Kessenich4016e382016-07-15 11:53:56 -06005015 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005016 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5017}
5018
John Kessenich55e7d112015-11-15 21:33:39 -07005019// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005020// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005021//
5022// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5023//
5024// Recursively walk the nodes. The nodes form a tree whose leaves are
5025// regular constants, which themselves are trees that createSpvConstant()
5026// recursively walks. So, this function walks the "top" of the tree:
5027// - emit specialization constant-building instructions for specConstant
5028// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005029spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005030{
John Kessenich7cc0e282016-03-20 00:46:02 -06005031 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005032
qining4f4bb812016-04-03 23:55:17 -04005033 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005034 if (! node.getQualifier().specConstant) {
5035 // hand off to the non-spec-constant path
5036 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5037 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005038 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005039 nextConst, false);
5040 }
5041
5042 // We now know we have a specialization constant to build
5043
John Kessenichd94c0032016-05-30 19:29:40 -06005044 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005045 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5046 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5047 std::vector<spv::Id> dimConstId;
5048 for (int dim = 0; dim < 3; ++dim) {
5049 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5050 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5051 if (specConst)
5052 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5053 }
5054 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5055 }
5056
5057 // An AST node labelled as specialization constant should be a symbol node.
5058 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5059 if (auto* sn = node.getAsSymbolNode()) {
5060 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005061 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5062 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5063 // will set the builder into spec constant op instruction generating mode.
5064 sub_tree->traverse(this);
5065 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005066 } else if (auto* const_union_array = &sn->getConstArray()){
5067 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005068 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5069 builder.addName(id, sn->getName().c_str());
5070 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005071 }
5072 }
qining4f4bb812016-04-03 23:55:17 -04005073
5074 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5075 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005076 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005077 exit(1);
5078 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005079}
5080
John Kessenich140f3df2015-06-26 16:58:36 -06005081// Use 'consts' as the flattened glslang source of scalar constants to recursively
5082// build the aggregate SPIR-V constant.
5083//
5084// If there are not enough elements present in 'consts', 0 will be substituted;
5085// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5086//
qining08408382016-03-21 09:51:37 -04005087spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005088{
5089 // vector of constants for SPIR-V
5090 std::vector<spv::Id> spvConsts;
5091
5092 // Type is used for struct and array constants
5093 spv::Id typeId = convertGlslangToSpvType(glslangType);
5094
5095 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005096 glslang::TType elementType(glslangType, 0);
5097 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005098 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005099 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005100 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005101 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005102 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005103 } else if (glslangType.getStruct()) {
5104 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5105 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005106 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005107 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005108 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5109 bool zero = nextConst >= consts.size();
5110 switch (glslangType.getBasicType()) {
5111 case glslang::EbtInt:
5112 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5113 break;
5114 case glslang::EbtUint:
5115 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5116 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005117 case glslang::EbtInt64:
5118 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5119 break;
5120 case glslang::EbtUint64:
5121 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5122 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005123 case glslang::EbtFloat:
5124 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5125 break;
5126 case glslang::EbtDouble:
5127 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5128 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005129#ifdef AMD_EXTENSIONS
5130 case glslang::EbtFloat16:
5131 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5132 break;
5133#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005134 case glslang::EbtBool:
5135 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5136 break;
5137 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005138 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005139 break;
5140 }
5141 ++nextConst;
5142 }
5143 } else {
5144 // we have a non-aggregate (scalar) constant
5145 bool zero = nextConst >= consts.size();
5146 spv::Id scalar = 0;
5147 switch (glslangType.getBasicType()) {
5148 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005149 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005150 break;
5151 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005152 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005153 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005154 case glslang::EbtInt64:
5155 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5156 break;
5157 case glslang::EbtUint64:
5158 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5159 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005160 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005161 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005162 break;
5163 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005164 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005165 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005166#ifdef AMD_EXTENSIONS
5167 case glslang::EbtFloat16:
5168 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5169 break;
5170#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005171 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005172 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005173 break;
5174 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005175 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005176 break;
5177 }
5178 ++nextConst;
5179 return scalar;
5180 }
5181
5182 return builder.makeCompositeConstant(typeId, spvConsts);
5183}
5184
John Kessenich7c1aa102015-10-15 13:29:11 -06005185// Return true if the node is a constant or symbol whose reading has no
5186// non-trivial observable cost or effect.
5187bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5188{
5189 // don't know what this is
5190 if (node == nullptr)
5191 return false;
5192
5193 // a constant is safe
5194 if (node->getAsConstantUnion() != nullptr)
5195 return true;
5196
5197 // not a symbol means non-trivial
5198 if (node->getAsSymbolNode() == nullptr)
5199 return false;
5200
5201 // a symbol, depends on what's being read
5202 switch (node->getType().getQualifier().storage) {
5203 case glslang::EvqTemporary:
5204 case glslang::EvqGlobal:
5205 case glslang::EvqIn:
5206 case glslang::EvqInOut:
5207 case glslang::EvqConst:
5208 case glslang::EvqConstReadOnly:
5209 case glslang::EvqUniform:
5210 return true;
5211 default:
5212 return false;
5213 }
qining25262b32016-05-06 17:25:16 -04005214}
John Kessenich7c1aa102015-10-15 13:29:11 -06005215
5216// A node is trivial if it is a single operation with no side effects.
5217// Error on the side of saying non-trivial.
5218// Return true if trivial.
5219bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5220{
5221 if (node == nullptr)
5222 return false;
5223
5224 // symbols and constants are trivial
5225 if (isTrivialLeaf(node))
5226 return true;
5227
5228 // otherwise, it needs to be a simple operation or one or two leaf nodes
5229
5230 // not a simple operation
5231 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5232 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5233 if (binaryNode == nullptr && unaryNode == nullptr)
5234 return false;
5235
5236 // not on leaf nodes
5237 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5238 return false;
5239
5240 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5241 return false;
5242 }
5243
5244 switch (node->getAsOperator()->getOp()) {
5245 case glslang::EOpLogicalNot:
5246 case glslang::EOpConvIntToBool:
5247 case glslang::EOpConvUintToBool:
5248 case glslang::EOpConvFloatToBool:
5249 case glslang::EOpConvDoubleToBool:
5250 case glslang::EOpEqual:
5251 case glslang::EOpNotEqual:
5252 case glslang::EOpLessThan:
5253 case glslang::EOpGreaterThan:
5254 case glslang::EOpLessThanEqual:
5255 case glslang::EOpGreaterThanEqual:
5256 case glslang::EOpIndexDirect:
5257 case glslang::EOpIndexDirectStruct:
5258 case glslang::EOpLogicalXor:
5259 case glslang::EOpAny:
5260 case glslang::EOpAll:
5261 return true;
5262 default:
5263 return false;
5264 }
5265}
5266
5267// Emit short-circuiting code, where 'right' is never evaluated unless
5268// the left side is true (for &&) or false (for ||).
5269spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5270{
5271 spv::Id boolTypeId = builder.makeBoolType();
5272
5273 // emit left operand
5274 builder.clearAccessChain();
5275 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005276 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005277
5278 // Operands to accumulate OpPhi operands
5279 std::vector<spv::Id> phiOperands;
5280 // accumulate left operand's phi information
5281 phiOperands.push_back(leftId);
5282 phiOperands.push_back(builder.getBuildPoint()->getId());
5283
5284 // Make the two kinds of operation symmetric with a "!"
5285 // || => emit "if (! left) result = right"
5286 // && => emit "if ( left) result = right"
5287 //
5288 // TODO: this runtime "not" for || could be avoided by adding functionality
5289 // to 'builder' to have an "else" without an "then"
5290 if (op == glslang::EOpLogicalOr)
5291 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5292
5293 // make an "if" based on the left value
5294 spv::Builder::If ifBuilder(leftId, builder);
5295
5296 // emit right operand as the "then" part of the "if"
5297 builder.clearAccessChain();
5298 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005299 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005300
5301 // accumulate left operand's phi information
5302 phiOperands.push_back(rightId);
5303 phiOperands.push_back(builder.getBuildPoint()->getId());
5304
5305 // finish the "if"
5306 ifBuilder.makeEndIf();
5307
5308 // phi together the two results
5309 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5310}
5311
Rex Xu9d93a232016-05-05 12:30:44 +08005312// Return type Id of the imported set of extended instructions corresponds to the name.
5313// Import this set if it has not been imported yet.
5314spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5315{
5316 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5317 return extBuiltinMap[name];
5318 else {
Rex Xu51596642016-09-21 18:56:12 +08005319 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005320 spv::Id extBuiltins = builder.import(name);
5321 extBuiltinMap[name] = extBuiltins;
5322 return extBuiltins;
5323 }
5324}
5325
John Kessenich140f3df2015-06-26 16:58:36 -06005326}; // end anonymous namespace
5327
5328namespace glslang {
5329
John Kessenich68d78fd2015-07-12 19:28:10 -06005330void GetSpirvVersion(std::string& version)
5331{
John Kessenich9e55f632015-07-15 10:03:39 -06005332 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005333 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005334 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005335 version = buf;
5336}
5337
John Kessenich140f3df2015-06-26 16:58:36 -06005338// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005339void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005340{
5341 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005342 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005343 if (out.fail())
5344 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005345 for (int i = 0; i < (int)spirv.size(); ++i) {
5346 unsigned int word = spirv[i];
5347 out.write((const char*)&word, 4);
5348 }
5349 out.close();
5350}
5351
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005352// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005353void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005354{
5355 std::ofstream out;
5356 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005357 if (out.fail())
5358 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005359 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005360 if (varName != nullptr) {
5361 out << "\t #pragma once" << std::endl;
5362 out << "const uint32_t " << varName << "[] = {" << std::endl;
5363 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005364 const int WORDS_PER_LINE = 8;
5365 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5366 out << "\t";
5367 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5368 const unsigned int word = spirv[i + j];
5369 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5370 if (i + j + 1 < (int)spirv.size()) {
5371 out << ",";
5372 }
5373 }
5374 out << std::endl;
5375 }
Flavio15017db2017-02-15 14:29:33 -08005376 if (varName != nullptr) {
5377 out << "};";
5378 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005379 out.close();
5380}
5381
John Kessenich140f3df2015-06-26 16:58:36 -06005382//
5383// Set up the glslang traversal
5384//
5385void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5386{
Lei Zhang17535f72016-05-04 15:55:59 -04005387 spv::SpvBuildLogger logger;
5388 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005389}
5390
Lei Zhang17535f72016-05-04 15:55:59 -04005391void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005392{
John Kessenich140f3df2015-06-26 16:58:36 -06005393 TIntermNode* root = intermediate.getTreeRoot();
5394
5395 if (root == 0)
5396 return;
5397
5398 glslang::GetThreadPoolAllocator().push();
5399
Lei Zhang17535f72016-05-04 15:55:59 -04005400 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005401 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005402 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005403 it.dumpSpv(spirv);
5404
5405 glslang::GetThreadPoolAllocator().pop();
5406}
5407
5408}; // end namespace glslang