blob: 1a300b525a6fc60b2372775bde3dd63776016759 [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::EbtSampler)
255 return spv::StorageClassUniformConstant;
256 else if (type.getBasicType() == glslang::EbtAtomicUint)
257 return spv::StorageClassAtomicCounter;
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 Kessenich5aa59e22016-06-17 15:50:47 -0600265 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600266 } else {
267 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700268 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
269 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
271 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::StorageClassFunction;
275 }
276 }
277}
278
279// Translate glslang sampler type to SPIR-V dimensionality.
280spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
281{
282 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700283 case glslang::Esd1D: return spv::Dim1D;
284 case glslang::Esd2D: return spv::Dim2D;
285 case glslang::Esd3D: return spv::Dim3D;
286 case glslang::EsdCube: return spv::DimCube;
287 case glslang::EsdRect: return spv::DimRect;
288 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700289 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::Dim2D;
293 }
294}
295
John Kessenichf6640762016-08-01 19:44:00 -0600296// Translate glslang precision to SPIR-V precision decorations.
297spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
John Kessenichf6640762016-08-01 19:44:00 -0600299 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700300 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600301 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::NoPrecision;
304 }
305}
306
John Kessenichf6640762016-08-01 19:44:00 -0600307// Translate glslang type to SPIR-V precision decorations.
308spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
309{
310 return TranslatePrecisionDecoration(type.getQualifier().precision);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V block decorations.
314spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
315{
316 if (type.getBasicType() == glslang::EbtBlock) {
317 switch (type.getQualifier().storage) {
318 case glslang::EvqUniform: return spv::DecorationBlock;
319 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
320 case glslang::EvqVaryingIn: return spv::DecorationBlock;
321 case glslang::EvqVaryingOut: return spv::DecorationBlock;
322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 break;
325 }
326 }
327
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329}
330
Rex Xu1da878f2016-02-21 20:59:01 +0800331// Translate glslang type to SPIR-V memory decorations.
332void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
333{
334 if (qualifier.coherent)
335 memory.push_back(spv::DecorationCoherent);
336 if (qualifier.volatil)
337 memory.push_back(spv::DecorationVolatile);
338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
David Netoa901ffe2016-06-08 14:11:40 +0100442// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
443// associated capabilities when required. For some built-in variables, a capability
444// is generated only when using the variable in an executable instruction, but not when
445// just declaring a struct member variable with it. This is true for PointSize,
446// ClipDistance, and CullDistance.
447spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600448{
449 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700450 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600451 // Defer adding the capability until the built-in is actually used.
452 if (! memberDeclaration) {
453 switch (glslangIntermediate->getStage()) {
454 case EShLangGeometry:
455 builder.addCapability(spv::CapabilityGeometryPointSize);
456 break;
457 case EShLangTessControl:
458 case EShLangTessEvaluation:
459 builder.addCapability(spv::CapabilityTessellationPointSize);
460 break;
461 default:
462 break;
463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 }
465 return spv::BuiltInPointSize;
466
John Kessenichebb50532016-05-16 19:22:05 -0600467 // These *Distance capabilities logically belong here, but if the member is declared and
468 // then never used, consumers of SPIR-V prefer the capability not be declared.
469 // They are now generated when used, rather than here when declared.
470 // Potentially, the specification should be more clear what the minimum
471 // use needed is to trigger the capability.
472 //
John Kessenich92187592016-02-01 13:45:25 -0700473 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100474 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600475 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInClipDistance;
477
478 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600480 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInCullDistance;
482
483 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500484 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation)
489 {
490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
493#endif
John Kessenich92187592016-02-01 13:45:25 -0700494 return spv::BuiltInViewportIndex;
495
John Kessenich5e801132016-02-15 11:09:46 -0700496 case glslang::EbvSampleId:
497 builder.addCapability(spv::CapabilitySampleRateShading);
498 return spv::BuiltInSampleId;
499
500 case glslang::EbvSamplePosition:
501 builder.addCapability(spv::CapabilitySampleRateShading);
502 return spv::BuiltInSamplePosition;
503
504 case glslang::EbvSampleMask:
505 builder.addCapability(spv::CapabilitySampleRateShading);
506 return spv::BuiltInSampleMask;
507
John Kessenich78a45572016-07-08 14:05:15 -0600508 case glslang::EbvLayer:
509 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800510#ifdef NV_EXTENSIONS
511 if (!memberDeclaration)
512 {
513 if (glslangIntermediate->getStage() == EShLangVertex ||
514 glslangIntermediate->getStage() == EShLangTessControl ||
515 glslangIntermediate->getStage() == EShLangTessEvaluation)
516 {
517 builder.addExtension(spv::E_SPV_NV_viewport_array2);
518 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
519 }
520 }
521#endif
John Kessenich78a45572016-07-08 14:05:15 -0600522 return spv::BuiltInLayer;
523
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvVertexId: return spv::BuiltInVertexId;
526 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700527 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
528 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800529
John Kessenichda581a22015-10-14 14:10:30 -0600530 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800531 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
532 builder.addCapability(spv::CapabilityDrawParameters);
533 return spv::BuiltInBaseVertex;
534
John Kessenichda581a22015-10-14 14:10:30 -0600535 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800536 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
537 builder.addCapability(spv::CapabilityDrawParameters);
538 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200539
John Kessenichda581a22015-10-14 14:10:30 -0600540 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800541 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
542 builder.addCapability(spv::CapabilityDrawParameters);
543 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200544
545 case glslang::EbvPrimitiveId:
546 if (glslangIntermediate->getStage() == EShLangFragment)
547 builder.addCapability(spv::CapabilityGeometry);
548 return spv::BuiltInPrimitiveId;
549
John Kessenich140f3df2015-06-26 16:58:36 -0600550 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
552 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
553 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
554 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
555 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
556 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
557 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600558 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
559 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
560 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
561 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
562 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
563 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
564 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
565 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupSize;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLocalInvocationId;
576
Rex Xu574ab042016-04-14 16:53:07 +0800577 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
579 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
580 return spv::BuiltInSubgroupEqMaskKHR;
581
Rex Xu574ab042016-04-14 16:53:07 +0800582 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800583 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
584 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
585 return spv::BuiltInSubgroupGeMaskKHR;
586
Rex Xu574ab042016-04-14 16:53:07 +0800587 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800588 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
589 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
590 return spv::BuiltInSubgroupGtMaskKHR;
591
Rex Xu574ab042016-04-14 16:53:07 +0800592 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800593 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
594 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
595 return spv::BuiltInSubgroupLeMaskKHR;
596
Rex Xu574ab042016-04-14 16:53:07 +0800597 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800598 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
599 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
600 return spv::BuiltInSubgroupLtMaskKHR;
601
Rex Xu9d93a232016-05-05 12:30:44 +0800602#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800603 case glslang::EbvBaryCoordNoPersp:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordNoPerspAMD;
606
607 case glslang::EbvBaryCoordNoPerspCentroid:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
610
611 case glslang::EbvBaryCoordNoPerspSample:
612 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
613 return spv::BuiltInBaryCoordNoPerspSampleAMD;
614
615 case glslang::EbvBaryCoordSmooth:
616 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
617 return spv::BuiltInBaryCoordSmoothAMD;
618
619 case glslang::EbvBaryCoordSmoothCentroid:
620 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
621 return spv::BuiltInBaryCoordSmoothCentroidAMD;
622
623 case glslang::EbvBaryCoordSmoothSample:
624 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
625 return spv::BuiltInBaryCoordSmoothSampleAMD;
626
627 case glslang::EbvBaryCoordPullModel:
628 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
629 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800630#endif
chaoc771d89f2017-01-13 01:10:53 -0800631
632#ifdef NV_EXTENSIONS
633 case glslang::EbvViewportMaskNV:
634 builder.addExtension(spv::E_SPV_NV_viewport_array2);
635 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
636 return spv::BuiltInViewportMaskNV;
637 case glslang::EbvSecondaryPositionNV:
638 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
640 return spv::BuiltInSecondaryPositionNV;
641 case glslang::EbvSecondaryViewportMaskNV:
642 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
643 builder.addCapability(spv::CapabilityShaderStereoViewNV);
644 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800645 case glslang::EbvPositionPerViewNV:
646 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
647 builder.addCapability(spv::CapabilityPerViewAttributesNV);
648 return spv::BuiltInPositionPerViewNV;
649 case glslang::EbvViewportMaskPerViewNV:
650 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
651 builder.addCapability(spv::CapabilityPerViewAttributesNV);
652 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800653#endif
John Kessenich4016e382016-07-15 11:53:56 -0600654 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600655 }
656}
657
Rex Xufc618912015-09-09 16:42:49 +0800658// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700659spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800660{
661 assert(type.getBasicType() == glslang::EbtSampler);
662
John Kessenich5d0fa972016-02-15 11:57:00 -0700663 // Check for capabilities
664 switch (type.getQualifier().layoutFormat) {
665 case glslang::ElfRg32f:
666 case glslang::ElfRg16f:
667 case glslang::ElfR11fG11fB10f:
668 case glslang::ElfR16f:
669 case glslang::ElfRgba16:
670 case glslang::ElfRgb10A2:
671 case glslang::ElfRg16:
672 case glslang::ElfRg8:
673 case glslang::ElfR16:
674 case glslang::ElfR8:
675 case glslang::ElfRgba16Snorm:
676 case glslang::ElfRg16Snorm:
677 case glslang::ElfRg8Snorm:
678 case glslang::ElfR16Snorm:
679 case glslang::ElfR8Snorm:
680
681 case glslang::ElfRg32i:
682 case glslang::ElfRg16i:
683 case glslang::ElfRg8i:
684 case glslang::ElfR16i:
685 case glslang::ElfR8i:
686
687 case glslang::ElfRgb10a2ui:
688 case glslang::ElfRg32ui:
689 case glslang::ElfRg16ui:
690 case glslang::ElfRg8ui:
691 case glslang::ElfR16ui:
692 case glslang::ElfR8ui:
693 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
694 break;
695
696 default:
697 break;
698 }
699
700 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800701 switch (type.getQualifier().layoutFormat) {
702 case glslang::ElfNone: return spv::ImageFormatUnknown;
703 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
704 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
705 case glslang::ElfR32f: return spv::ImageFormatR32f;
706 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
707 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
708 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
709 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
710 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
711 case glslang::ElfR16f: return spv::ImageFormatR16f;
712 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
713 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
714 case glslang::ElfRg16: return spv::ImageFormatRg16;
715 case glslang::ElfRg8: return spv::ImageFormatRg8;
716 case glslang::ElfR16: return spv::ImageFormatR16;
717 case glslang::ElfR8: return spv::ImageFormatR8;
718 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
719 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
720 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
721 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
722 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
723 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
724 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
725 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
726 case glslang::ElfR32i: return spv::ImageFormatR32i;
727 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
728 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
729 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
730 case glslang::ElfR16i: return spv::ImageFormatR16i;
731 case glslang::ElfR8i: return spv::ImageFormatR8i;
732 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
733 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
734 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
735 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
736 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
737 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
738 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
739 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
740 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
741 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600742 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800743 }
744}
745
qining25262b32016-05-06 17:25:16 -0400746// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700747// descriptor set.
748bool IsDescriptorResource(const glslang::TType& type)
749{
John Kessenichf7497e22016-03-08 21:36:22 -0700750 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700751 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700752 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700753
754 // non block...
755 // basically samplerXXX/subpass/sampler/texture are all included
756 // if they are the global-scope-class, not the function parameter
757 // (or local, if they ever exist) class.
758 if (type.getBasicType() == glslang::EbtSampler)
759 return type.getQualifier().isUniformOrBuffer();
760
761 // None of the above.
762 return false;
763}
764
John Kesseniche0b6cad2015-12-24 10:30:13 -0700765void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
766{
767 if (child.layoutMatrix == glslang::ElmNone)
768 child.layoutMatrix = parent.layoutMatrix;
769
770 if (parent.invariant)
771 child.invariant = true;
772 if (parent.nopersp)
773 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800774#ifdef AMD_EXTENSIONS
775 if (parent.explicitInterp)
776 child.explicitInterp = true;
777#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700778 if (parent.flat)
779 child.flat = true;
780 if (parent.centroid)
781 child.centroid = true;
782 if (parent.patch)
783 child.patch = true;
784 if (parent.sample)
785 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800786 if (parent.coherent)
787 child.coherent = true;
788 if (parent.volatil)
789 child.volatil = true;
790 if (parent.restrict)
791 child.restrict = true;
792 if (parent.readonly)
793 child.readonly = true;
794 if (parent.writeonly)
795 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700796}
797
John Kessenichf2b7f332016-09-01 17:05:23 -0600798bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700799{
John Kessenich7b9fa252016-01-21 18:56:57 -0700800 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600801 // - struct members might inherit from a struct declaration
802 // (note that non-block structs don't explicitly inherit,
803 // only implicitly, meaning no decoration involved)
804 // - affect decorations on the struct members
805 // (note smooth does not, and expecting something like volatile
806 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700807 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600808 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700809}
810
John Kessenich140f3df2015-06-26 16:58:36 -0600811//
812// Implement the TGlslangToSpvTraverser class.
813//
814
Lei Zhang17535f72016-05-04 15:55:59 -0400815TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600816 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
817 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400818 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700819 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600820 glslangIntermediate(glslangIntermediate)
821{
822 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
823
824 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700825 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600826 stdBuiltins = builder.import("GLSL.std.450");
827 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600828 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
829 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600830
831 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600832 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
833 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600834 builder.addSourceExtension(it->c_str());
835
836 // Add the top-level modes for this shader.
837
John Kessenich92187592016-02-01 13:45:25 -0700838 if (glslangIntermediate->getXfbMode()) {
839 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600840 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700841 }
John Kessenich140f3df2015-06-26 16:58:36 -0600842
843 unsigned int mode;
844 switch (glslangIntermediate->getStage()) {
845 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600846 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600847 break;
848
849 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600850 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600851 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
852 break;
853
854 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600855 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600856 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700857 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
858 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
859 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600860 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600861 }
John Kessenich4016e382016-07-15 11:53:56 -0600862 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600863 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
864
John Kesseniche6903322015-10-13 16:29:02 -0600865 switch (glslangIntermediate->getVertexSpacing()) {
866 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
867 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
868 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600869 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600870 }
John Kessenich4016e382016-07-15 11:53:56 -0600871 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600872 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
873
874 switch (glslangIntermediate->getVertexOrder()) {
875 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
876 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600877 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600878 }
John Kessenich4016e382016-07-15 11:53:56 -0600879 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600880 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
881
882 if (glslangIntermediate->getPointMode())
883 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600884 break;
885
886 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600887 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600888 switch (glslangIntermediate->getInputPrimitive()) {
889 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
890 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
891 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700892 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600893 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600894 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600895 }
John Kessenich4016e382016-07-15 11:53:56 -0600896 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600897 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600898
John Kessenich140f3df2015-06-26 16:58:36 -0600899 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
900
901 switch (glslangIntermediate->getOutputPrimitive()) {
902 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
903 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
904 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
910 break;
911
912 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600913 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600914 if (glslangIntermediate->getPixelCenterInteger())
915 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600916
John Kessenich140f3df2015-06-26 16:58:36 -0600917 if (glslangIntermediate->getOriginUpperLeft())
918 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600919 else
920 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600921
922 if (glslangIntermediate->getEarlyFragmentTests())
923 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
924
925 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600926 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
927 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600928 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600929 }
John Kessenich4016e382016-07-15 11:53:56 -0600930 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600931 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
932
933 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
934 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600935 break;
936
937 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600938 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600939 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
940 glslangIntermediate->getLocalSize(1),
941 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600942 break;
943
944 default:
945 break;
946 }
John Kessenich140f3df2015-06-26 16:58:36 -0600947}
948
John Kessenichfca82622016-11-26 13:23:20 -0700949// Finish creating SPV, after the traversal is complete.
950void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700951{
John Kessenich517fe7a2016-11-26 13:31:47 -0700952 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700953 builder.setBuildPoint(shaderEntry->getLastBlock());
954 builder.leaveFunction();
955 }
956
John Kessenich7ba63412015-12-20 17:37:07 -0700957 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100958 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
959 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700960
qiningda397332016-03-09 19:54:03 -0500961 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700962}
963
John Kessenichfca82622016-11-26 13:23:20 -0700964// Write the SPV into 'out'.
965void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600966{
John Kessenichfca82622016-11-26 13:23:20 -0700967 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600968}
969
970//
971// Implement the traversal functions.
972//
973// Return true from interior nodes to have the external traversal
974// continue on to children. Return false if children were
975// already processed.
976//
977
978//
qining25262b32016-05-06 17:25:16 -0400979// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600980// - uniform/input reads
981// - output writes
982// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
983// - something simple that degenerates into the last bullet
984//
985void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
986{
qining75d1d802016-04-06 14:42:01 -0400987 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
988 if (symbol->getType().getQualifier().isSpecConstant())
989 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
990
John Kessenich140f3df2015-06-26 16:58:36 -0600991 // getSymbolId() will set up all the IO decorations on the first call.
992 // Formal function parameters were mapped during makeFunctions().
993 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700994
995 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
996 if (builder.isPointer(id)) {
997 spv::StorageClass sc = builder.getStorageClass(id);
998 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
999 iOSet.insert(id);
1000 }
1001
1002 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001003 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001004 // Prepare to generate code for the access
1005
1006 // L-value chains will be computed left to right. We're on the symbol now,
1007 // which is the left-most part of the access chain, so now is "clear" time,
1008 // followed by setting the base.
1009 builder.clearAccessChain();
1010
1011 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001012 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001013 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001014 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001015 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001016 // These are also pure R-values.
1017 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001018 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001019 builder.setAccessChainRValue(id);
1020 else
1021 builder.setAccessChainLValue(id);
1022 }
1023}
1024
1025bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1026{
qining40887662016-04-03 22:20:42 -04001027 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1028 if (node->getType().getQualifier().isSpecConstant())
1029 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1030
John Kessenich140f3df2015-06-26 16:58:36 -06001031 // First, handle special cases
1032 switch (node->getOp()) {
1033 case glslang::EOpAssign:
1034 case glslang::EOpAddAssign:
1035 case glslang::EOpSubAssign:
1036 case glslang::EOpMulAssign:
1037 case glslang::EOpVectorTimesMatrixAssign:
1038 case glslang::EOpVectorTimesScalarAssign:
1039 case glslang::EOpMatrixTimesScalarAssign:
1040 case glslang::EOpMatrixTimesMatrixAssign:
1041 case glslang::EOpDivAssign:
1042 case glslang::EOpModAssign:
1043 case glslang::EOpAndAssign:
1044 case glslang::EOpInclusiveOrAssign:
1045 case glslang::EOpExclusiveOrAssign:
1046 case glslang::EOpLeftShiftAssign:
1047 case glslang::EOpRightShiftAssign:
1048 // A bin-op assign "a += b" means the same thing as "a = a + b"
1049 // where a is evaluated before b. For a simple assignment, GLSL
1050 // says to evaluate the left before the right. So, always, left
1051 // node then right node.
1052 {
1053 // get the left l-value, save it away
1054 builder.clearAccessChain();
1055 node->getLeft()->traverse(this);
1056 spv::Builder::AccessChain lValue = builder.getAccessChain();
1057
1058 // evaluate the right
1059 builder.clearAccessChain();
1060 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001061 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001062
1063 if (node->getOp() != glslang::EOpAssign) {
1064 // the left is also an r-value
1065 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001066 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001067
1068 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001069 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001070 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001071 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1072 node->getType().getBasicType());
1073
1074 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001075 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001076 }
1077
1078 // store the result
1079 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001080 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001081
1082 // assignments are expressions having an rValue after they are evaluated...
1083 builder.clearAccessChain();
1084 builder.setAccessChainRValue(rValue);
1085 }
1086 return false;
1087 case glslang::EOpIndexDirect:
1088 case glslang::EOpIndexDirectStruct:
1089 {
1090 // Get the left part of the access chain.
1091 node->getLeft()->traverse(this);
1092
1093 // Add the next element in the chain
1094
David Netoa901ffe2016-06-08 14:11:40 +01001095 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001096 if (! node->getLeft()->getType().isArray() &&
1097 node->getLeft()->getType().isVector() &&
1098 node->getOp() == glslang::EOpIndexDirect) {
1099 // This is essentially a hard-coded vector swizzle of size 1,
1100 // so short circuit the access-chain stuff with a swizzle.
1101 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001102 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001103 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001104 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001105 int spvIndex = glslangIndex;
1106 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1107 node->getOp() == glslang::EOpIndexDirectStruct)
1108 {
1109 // This may be, e.g., an anonymous block-member selection, which generally need
1110 // index remapping due to hidden members in anonymous blocks.
1111 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1112 assert(remapper.size() > 0);
1113 spvIndex = remapper[glslangIndex];
1114 }
John Kessenichebb50532016-05-16 19:22:05 -06001115
David Netoa901ffe2016-06-08 14:11:40 +01001116 // normal case for indexing array or structure or block
1117 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1118
1119 // Add capabilities here for accessing PointSize and clip/cull distance.
1120 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001121 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001122 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001123 }
1124 }
1125 return false;
1126 case glslang::EOpIndexIndirect:
1127 {
1128 // Structure or array or vector indirection.
1129 // Will use native SPIR-V access-chain for struct and array indirection;
1130 // matrices are arrays of vectors, so will also work for a matrix.
1131 // Will use the access chain's 'component' for variable index into a vector.
1132
1133 // This adapter is building access chains left to right.
1134 // Set up the access chain to the left.
1135 node->getLeft()->traverse(this);
1136
1137 // save it so that computing the right side doesn't trash it
1138 spv::Builder::AccessChain partial = builder.getAccessChain();
1139
1140 // compute the next index in the chain
1141 builder.clearAccessChain();
1142 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001143 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 // restore the saved access chain
1146 builder.setAccessChain(partial);
1147
1148 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001149 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001150 else
John Kessenichfa668da2015-09-13 14:46:30 -06001151 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001152 }
1153 return false;
1154 case glslang::EOpVectorSwizzle:
1155 {
1156 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001157 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001158 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001159 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001160 }
1161 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001162 case glslang::EOpMatrixSwizzle:
1163 logger->missingFunctionality("matrix swizzle");
1164 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001165 case glslang::EOpLogicalOr:
1166 case glslang::EOpLogicalAnd:
1167 {
1168
1169 // These may require short circuiting, but can sometimes be done as straight
1170 // binary operations. The right operand must be short circuited if it has
1171 // side effects, and should probably be if it is complex.
1172 if (isTrivial(node->getRight()->getAsTyped()))
1173 break; // handle below as a normal binary operation
1174 // otherwise, we need to do dynamic short circuiting on the right operand
1175 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1176 builder.clearAccessChain();
1177 builder.setAccessChainRValue(result);
1178 }
1179 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001180 default:
1181 break;
1182 }
1183
1184 // Assume generic binary op...
1185
John Kessenich32cfd492016-02-02 12:37:46 -07001186 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001187 builder.clearAccessChain();
1188 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001189 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001190
John Kessenich32cfd492016-02-02 12:37:46 -07001191 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001192 builder.clearAccessChain();
1193 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001194 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001195
John Kessenich32cfd492016-02-02 12:37:46 -07001196 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001197 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001198 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001199 convertGlslangToSpvType(node->getType()), left, right,
1200 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001201
John Kessenich50e57562015-12-21 21:21:11 -07001202 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001203 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001204 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001205 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001206 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001207 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001208 return false;
1209 }
John Kessenich140f3df2015-06-26 16:58:36 -06001210}
1211
1212bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1213{
qining40887662016-04-03 22:20:42 -04001214 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1215 if (node->getType().getQualifier().isSpecConstant())
1216 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1217
John Kessenichfc51d282015-08-19 13:34:18 -06001218 spv::Id result = spv::NoResult;
1219
1220 // try texturing first
1221 result = createImageTextureFunctionCall(node);
1222 if (result != spv::NoResult) {
1223 builder.clearAccessChain();
1224 builder.setAccessChainRValue(result);
1225
1226 return false; // done with this node
1227 }
1228
1229 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001230
1231 if (node->getOp() == glslang::EOpArrayLength) {
1232 // Quite special; won't want to evaluate the operand.
1233
1234 // Normal .length() would have been constant folded by the front-end.
1235 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001236 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001237 assert(node->getOperand()->getType().isRuntimeSizedArray());
1238 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1239 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001240 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1241 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001242
1243 builder.clearAccessChain();
1244 builder.setAccessChainRValue(length);
1245
1246 return false;
1247 }
1248
John Kessenichfc51d282015-08-19 13:34:18 -06001249 // Start by evaluating the operand
1250
John Kessenich8c8505c2016-07-26 12:50:38 -06001251 // Does it need a swizzle inversion? If so, evaluation is inverted;
1252 // operate first on the swizzle base, then apply the swizzle.
1253 spv::Id invertedType = spv::NoType;
1254 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1255 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1256 invertedType = getInvertedSwizzleType(*node->getOperand());
1257
John Kessenich140f3df2015-06-26 16:58:36 -06001258 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001259 if (invertedType != spv::NoType)
1260 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1261 else
1262 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001263
Rex Xufc618912015-09-09 16:42:49 +08001264 spv::Id operand = spv::NoResult;
1265
1266 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1267 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001268 node->getOp() == glslang::EOpAtomicCounter ||
1269 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001270 operand = builder.accessChainGetLValue(); // Special case l-value operands
1271 else
John Kessenich32cfd492016-02-02 12:37:46 -07001272 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001273
John Kessenichf6640762016-08-01 19:44:00 -06001274 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001275 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001276
1277 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001278 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001279 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001280
1281 // if not, then possibly an operation
1282 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001283 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001284
1285 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001286 if (invertedType)
1287 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1288
John Kessenich140f3df2015-06-26 16:58:36 -06001289 builder.clearAccessChain();
1290 builder.setAccessChainRValue(result);
1291
1292 return false; // done with this node
1293 }
1294
1295 // it must be a special case, check...
1296 switch (node->getOp()) {
1297 case glslang::EOpPostIncrement:
1298 case glslang::EOpPostDecrement:
1299 case glslang::EOpPreIncrement:
1300 case glslang::EOpPreDecrement:
1301 {
1302 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001303 spv::Id one = 0;
1304 if (node->getBasicType() == glslang::EbtFloat)
1305 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001306 else if (node->getBasicType() == glslang::EbtDouble)
1307 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001308#ifdef AMD_EXTENSIONS
1309 else if (node->getBasicType() == glslang::EbtFloat16)
1310 one = builder.makeFloat16Constant(1.0F);
1311#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001312 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1313 one = builder.makeInt64Constant(1);
1314 else
1315 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001316 glslang::TOperator op;
1317 if (node->getOp() == glslang::EOpPreIncrement ||
1318 node->getOp() == glslang::EOpPostIncrement)
1319 op = glslang::EOpAdd;
1320 else
1321 op = glslang::EOpSub;
1322
John Kessenichf6640762016-08-01 19:44:00 -06001323 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001324 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001325 convertGlslangToSpvType(node->getType()), operand, one,
1326 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001327 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001328
1329 // The result of operation is always stored, but conditionally the
1330 // consumed result. The consumed result is always an r-value.
1331 builder.accessChainStore(result);
1332 builder.clearAccessChain();
1333 if (node->getOp() == glslang::EOpPreIncrement ||
1334 node->getOp() == glslang::EOpPreDecrement)
1335 builder.setAccessChainRValue(result);
1336 else
1337 builder.setAccessChainRValue(operand);
1338 }
1339
1340 return false;
1341
1342 case glslang::EOpEmitStreamVertex:
1343 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1344 return false;
1345 case glslang::EOpEndStreamPrimitive:
1346 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1347 return false;
1348
1349 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001350 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001351 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001352 }
John Kessenich140f3df2015-06-26 16:58:36 -06001353}
1354
1355bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1356{
qining27e04a02016-04-14 16:40:20 -04001357 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1358 if (node->getType().getQualifier().isSpecConstant())
1359 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1360
John Kessenichfc51d282015-08-19 13:34:18 -06001361 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001362 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1363 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001364
1365 // try texturing
1366 result = createImageTextureFunctionCall(node);
1367 if (result != spv::NoResult) {
1368 builder.clearAccessChain();
1369 builder.setAccessChainRValue(result);
1370
1371 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001372 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001373 // "imageStore" is a special case, which has no result
1374 return false;
1375 }
John Kessenichfc51d282015-08-19 13:34:18 -06001376
John Kessenich140f3df2015-06-26 16:58:36 -06001377 glslang::TOperator binOp = glslang::EOpNull;
1378 bool reduceComparison = true;
1379 bool isMatrix = false;
1380 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001381 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 assert(node->getOp());
1384
John Kessenichf6640762016-08-01 19:44:00 -06001385 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 switch (node->getOp()) {
1388 case glslang::EOpSequence:
1389 {
1390 if (preVisit)
1391 ++sequenceDepth;
1392 else
1393 --sequenceDepth;
1394
1395 if (sequenceDepth == 1) {
1396 // If this is the parent node of all the functions, we want to see them
1397 // early, so all call points have actual SPIR-V functions to reference.
1398 // In all cases, still let the traverser visit the children for us.
1399 makeFunctions(node->getAsAggregate()->getSequence());
1400
John Kessenich6fccb3c2016-09-19 16:01:41 -06001401 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001402 // anything else gets there, so visit out of order, doing them all now.
1403 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1404
John Kessenich6a60c2f2016-12-08 21:01:59 -07001405 // 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 -06001406 // so do them manually.
1407 visitFunctions(node->getAsAggregate()->getSequence());
1408
1409 return false;
1410 }
1411
1412 return true;
1413 }
1414 case glslang::EOpLinkerObjects:
1415 {
1416 if (visit == glslang::EvPreVisit)
1417 linkageOnly = true;
1418 else
1419 linkageOnly = false;
1420
1421 return true;
1422 }
1423 case glslang::EOpComma:
1424 {
1425 // processing from left to right naturally leaves the right-most
1426 // lying around in the access chain
1427 glslang::TIntermSequence& glslangOperands = node->getSequence();
1428 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1429 glslangOperands[i]->traverse(this);
1430
1431 return false;
1432 }
1433 case glslang::EOpFunction:
1434 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001435 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001436 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001437 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001438 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001439 } else {
1440 handleFunctionEntry(node);
1441 }
1442 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001443 if (inEntryPoint)
1444 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001445 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001446 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001447 }
1448
1449 return true;
1450 case glslang::EOpParameters:
1451 // Parameters will have been consumed by EOpFunction processing, but not
1452 // the body, so we still visited the function node's children, making this
1453 // child redundant.
1454 return false;
1455 case glslang::EOpFunctionCall:
1456 {
1457 if (node->isUserDefined())
1458 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001459 // 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 -07001460 if (result) {
1461 builder.clearAccessChain();
1462 builder.setAccessChainRValue(result);
1463 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001464 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001465
1466 return false;
1467 }
1468 case glslang::EOpConstructMat2x2:
1469 case glslang::EOpConstructMat2x3:
1470 case glslang::EOpConstructMat2x4:
1471 case glslang::EOpConstructMat3x2:
1472 case glslang::EOpConstructMat3x3:
1473 case glslang::EOpConstructMat3x4:
1474 case glslang::EOpConstructMat4x2:
1475 case glslang::EOpConstructMat4x3:
1476 case glslang::EOpConstructMat4x4:
1477 case glslang::EOpConstructDMat2x2:
1478 case glslang::EOpConstructDMat2x3:
1479 case glslang::EOpConstructDMat2x4:
1480 case glslang::EOpConstructDMat3x2:
1481 case glslang::EOpConstructDMat3x3:
1482 case glslang::EOpConstructDMat3x4:
1483 case glslang::EOpConstructDMat4x2:
1484 case glslang::EOpConstructDMat4x3:
1485 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001486#ifdef AMD_EXTENSIONS
1487 case glslang::EOpConstructF16Mat2x2:
1488 case glslang::EOpConstructF16Mat2x3:
1489 case glslang::EOpConstructF16Mat2x4:
1490 case glslang::EOpConstructF16Mat3x2:
1491 case glslang::EOpConstructF16Mat3x3:
1492 case glslang::EOpConstructF16Mat3x4:
1493 case glslang::EOpConstructF16Mat4x2:
1494 case glslang::EOpConstructF16Mat4x3:
1495 case glslang::EOpConstructF16Mat4x4:
1496#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001497 isMatrix = true;
1498 // fall through
1499 case glslang::EOpConstructFloat:
1500 case glslang::EOpConstructVec2:
1501 case glslang::EOpConstructVec3:
1502 case glslang::EOpConstructVec4:
1503 case glslang::EOpConstructDouble:
1504 case glslang::EOpConstructDVec2:
1505 case glslang::EOpConstructDVec3:
1506 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001507#ifdef AMD_EXTENSIONS
1508 case glslang::EOpConstructFloat16:
1509 case glslang::EOpConstructF16Vec2:
1510 case glslang::EOpConstructF16Vec3:
1511 case glslang::EOpConstructF16Vec4:
1512#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001513 case glslang::EOpConstructBool:
1514 case glslang::EOpConstructBVec2:
1515 case glslang::EOpConstructBVec3:
1516 case glslang::EOpConstructBVec4:
1517 case glslang::EOpConstructInt:
1518 case glslang::EOpConstructIVec2:
1519 case glslang::EOpConstructIVec3:
1520 case glslang::EOpConstructIVec4:
1521 case glslang::EOpConstructUint:
1522 case glslang::EOpConstructUVec2:
1523 case glslang::EOpConstructUVec3:
1524 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001525 case glslang::EOpConstructInt64:
1526 case glslang::EOpConstructI64Vec2:
1527 case glslang::EOpConstructI64Vec3:
1528 case glslang::EOpConstructI64Vec4:
1529 case glslang::EOpConstructUint64:
1530 case glslang::EOpConstructU64Vec2:
1531 case glslang::EOpConstructU64Vec3:
1532 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001533 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001534 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001535 {
1536 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001537 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001538 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001539 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001540 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001541 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001542 std::vector<spv::Id> constituents;
1543 for (int c = 0; c < (int)arguments.size(); ++c)
1544 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001545 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001546 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001547 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001548 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001549 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001550
1551 builder.clearAccessChain();
1552 builder.setAccessChainRValue(constructed);
1553
1554 return false;
1555 }
1556
1557 // These six are component-wise compares with component-wise results.
1558 // Forward on to createBinaryOperation(), requesting a vector result.
1559 case glslang::EOpLessThan:
1560 case glslang::EOpGreaterThan:
1561 case glslang::EOpLessThanEqual:
1562 case glslang::EOpGreaterThanEqual:
1563 case glslang::EOpVectorEqual:
1564 case glslang::EOpVectorNotEqual:
1565 {
1566 // Map the operation to a binary
1567 binOp = node->getOp();
1568 reduceComparison = false;
1569 switch (node->getOp()) {
1570 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1571 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1572 default: binOp = node->getOp(); break;
1573 }
1574
1575 break;
1576 }
1577 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001578 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001579 binOp = glslang::EOpMul;
1580 break;
1581 case glslang::EOpOuterProduct:
1582 // two vectors multiplied to make a matrix
1583 binOp = glslang::EOpOuterProduct;
1584 break;
1585 case glslang::EOpDot:
1586 {
qining25262b32016-05-06 17:25:16 -04001587 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001588 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001589 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001590 binOp = glslang::EOpMul;
1591 break;
1592 }
1593 case glslang::EOpMod:
1594 // when an aggregate, this is the floating-point mod built-in function,
1595 // which can be emitted by the one in createBinaryOperation()
1596 binOp = glslang::EOpMod;
1597 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001598 case glslang::EOpEmitVertex:
1599 case glslang::EOpEndPrimitive:
1600 case glslang::EOpBarrier:
1601 case glslang::EOpMemoryBarrier:
1602 case glslang::EOpMemoryBarrierAtomicCounter:
1603 case glslang::EOpMemoryBarrierBuffer:
1604 case glslang::EOpMemoryBarrierImage:
1605 case glslang::EOpMemoryBarrierShared:
1606 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001607 case glslang::EOpAllMemoryBarrierWithGroupSync:
1608 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1609 case glslang::EOpWorkgroupMemoryBarrier:
1610 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001611 noReturnValue = true;
1612 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1613 break;
1614
John Kessenich426394d2015-07-23 10:22:48 -06001615 case glslang::EOpAtomicAdd:
1616 case glslang::EOpAtomicMin:
1617 case glslang::EOpAtomicMax:
1618 case glslang::EOpAtomicAnd:
1619 case glslang::EOpAtomicOr:
1620 case glslang::EOpAtomicXor:
1621 case glslang::EOpAtomicExchange:
1622 case glslang::EOpAtomicCompSwap:
1623 atomic = true;
1624 break;
1625
John Kessenich140f3df2015-06-26 16:58:36 -06001626 default:
1627 break;
1628 }
1629
1630 //
1631 // See if it maps to a regular operation.
1632 //
John Kessenich140f3df2015-06-26 16:58:36 -06001633 if (binOp != glslang::EOpNull) {
1634 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1635 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1636 assert(left && right);
1637
1638 builder.clearAccessChain();
1639 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001640 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001641
1642 builder.clearAccessChain();
1643 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001644 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001645
qining25262b32016-05-06 17:25:16 -04001646 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001647 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001648 left->getType().getBasicType(), reduceComparison);
1649
1650 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001651 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001652 builder.clearAccessChain();
1653 builder.setAccessChainRValue(result);
1654
1655 return false;
1656 }
1657
John Kessenich426394d2015-07-23 10:22:48 -06001658 //
1659 // Create the list of operands.
1660 //
John Kessenich140f3df2015-06-26 16:58:36 -06001661 glslang::TIntermSequence& glslangOperands = node->getSequence();
1662 std::vector<spv::Id> operands;
1663 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001664 // special case l-value operands; there are just a few
1665 bool lvalue = false;
1666 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001667 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001668 case glslang::EOpModf:
1669 if (arg == 1)
1670 lvalue = true;
1671 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001672 case glslang::EOpInterpolateAtSample:
1673 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001674#ifdef AMD_EXTENSIONS
1675 case glslang::EOpInterpolateAtVertex:
1676#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001677 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001678 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001679
1680 // Does it need a swizzle inversion? If so, evaluation is inverted;
1681 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001682 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001683 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1684 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1685 }
Rex Xu7a26c172015-12-08 17:12:09 +08001686 break;
Rex Xud4782c12015-09-06 16:30:11 +08001687 case glslang::EOpAtomicAdd:
1688 case glslang::EOpAtomicMin:
1689 case glslang::EOpAtomicMax:
1690 case glslang::EOpAtomicAnd:
1691 case glslang::EOpAtomicOr:
1692 case glslang::EOpAtomicXor:
1693 case glslang::EOpAtomicExchange:
1694 case glslang::EOpAtomicCompSwap:
1695 if (arg == 0)
1696 lvalue = true;
1697 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001698 case glslang::EOpAddCarry:
1699 case glslang::EOpSubBorrow:
1700 if (arg == 2)
1701 lvalue = true;
1702 break;
1703 case glslang::EOpUMulExtended:
1704 case glslang::EOpIMulExtended:
1705 if (arg >= 2)
1706 lvalue = true;
1707 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001708 default:
1709 break;
1710 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001711 builder.clearAccessChain();
1712 if (invertedType != spv::NoType && arg == 0)
1713 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1714 else
1715 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 if (lvalue)
1717 operands.push_back(builder.accessChainGetLValue());
1718 else
John Kessenich32cfd492016-02-02 12:37:46 -07001719 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001720 }
John Kessenich426394d2015-07-23 10:22:48 -06001721
1722 if (atomic) {
1723 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001724 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001725 } else {
1726 // Pass through to generic operations.
1727 switch (glslangOperands.size()) {
1728 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001729 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001730 break;
1731 case 1:
qining25262b32016-05-06 17:25:16 -04001732 result = createUnaryOperation(
1733 node->getOp(), precision,
1734 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001735 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001736 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001737 break;
1738 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001739 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001740 break;
1741 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001742 if (invertedType)
1743 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 }
1745
1746 if (noReturnValue)
1747 return false;
1748
1749 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001750 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001751 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001752 } else {
1753 builder.clearAccessChain();
1754 builder.setAccessChainRValue(result);
1755 return false;
1756 }
1757}
1758
John Kessenich433e9ff2017-01-26 20:31:11 -07001759// This path handles both if-then-else and ?:
1760// The if-then-else has a node type of void, while
1761// ?: has either a void or a non-void node type
1762//
1763// Leaving the result, when not void:
1764// GLSL only has r-values as the result of a :?, but
1765// if we have an l-value, that can be more efficient if it will
1766// become the base of a complex r-value expression, because the
1767// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001768bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1769{
John Kessenich433e9ff2017-01-26 20:31:11 -07001770 // See if it simple and safe to generate OpSelect instead of using control flow.
1771 // Crucially, side effects must be avoided, and there are performance trade-offs.
1772 // Return true if good idea (and safe) for OpSelect, false otherwise.
1773 const auto selectPolicy = [&]() -> bool {
1774 if (node->getBasicType() == glslang::EbtVoid)
1775 return false;
1776
1777 if (node->getTrueBlock() == nullptr ||
1778 node->getFalseBlock() == nullptr)
1779 return false;
1780
1781 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1782 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1783
1784 // return true if a single operand to ? : is okay for OpSelect
1785 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001786 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001787 };
1788
1789 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1790 operandOkay(node->getFalseBlock()->getAsTyped());
1791 };
1792
1793 // Emit OpSelect for this selection.
1794 const auto handleAsOpSelect = [&]() {
1795 node->getCondition()->traverse(this);
1796 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1797 node->getTrueBlock()->traverse(this);
1798 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1799 node->getFalseBlock()->traverse(this);
1800 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1801
1802 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1803 builder.clearAccessChain();
1804 builder.setAccessChainRValue(select);
1805 };
1806
1807 // Try for OpSelect
1808
1809 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001810 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1811 if (node->getType().getQualifier().isSpecConstant())
1812 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1813
John Kessenich433e9ff2017-01-26 20:31:11 -07001814 handleAsOpSelect();
1815 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001816 }
1817
John Kessenich433e9ff2017-01-26 20:31:11 -07001818 // Instead, emit control flow...
1819
1820 // Don't handle results as temporaries, because there will be two names
1821 // and better to leave SSA to later passes.
1822 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1823 ? spv::NoResult
1824 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1825
John Kessenich140f3df2015-06-26 16:58:36 -06001826 // emit the condition before doing anything with selection
1827 node->getCondition()->traverse(this);
1828
1829 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001830 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001831
John Kessenich433e9ff2017-01-26 20:31:11 -07001832 // emit the "then" statement
1833 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001834 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001835 if (result != spv::NoResult)
1836 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001837 }
1838
John Kessenich433e9ff2017-01-26 20:31:11 -07001839 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001840 ifBuilder.makeBeginElse();
1841 // emit the "else" statement
1842 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001843 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001844 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001845 }
1846
John Kessenich433e9ff2017-01-26 20:31:11 -07001847 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001848 ifBuilder.makeEndIf();
1849
John Kessenich433e9ff2017-01-26 20:31:11 -07001850 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001851 // GLSL only has r-values as the result of a :?, but
1852 // if we have an l-value, that can be more efficient if it will
1853 // become the base of a complex r-value expression, because the
1854 // next layer copies r-values into memory to use the access-chain mechanism
1855 builder.clearAccessChain();
1856 builder.setAccessChainLValue(result);
1857 }
1858
1859 return false;
1860}
1861
1862bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1863{
1864 // emit and get the condition before doing anything with switch
1865 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001866 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001867
1868 // browse the children to sort out code segments
1869 int defaultSegment = -1;
1870 std::vector<TIntermNode*> codeSegments;
1871 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1872 std::vector<int> caseValues;
1873 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1874 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1875 TIntermNode* child = *c;
1876 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001877 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001878 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001879 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001880 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1881 } else
1882 codeSegments.push_back(child);
1883 }
1884
qining25262b32016-05-06 17:25:16 -04001885 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001886 // statements between the last case and the end of the switch statement
1887 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1888 (int)codeSegments.size() == defaultSegment)
1889 codeSegments.push_back(nullptr);
1890
1891 // make the switch statement
1892 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001893 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001894
1895 // emit all the code in the segments
1896 breakForLoop.push(false);
1897 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1898 builder.nextSwitchSegment(segmentBlocks, s);
1899 if (codeSegments[s])
1900 codeSegments[s]->traverse(this);
1901 else
1902 builder.addSwitchBreak();
1903 }
1904 breakForLoop.pop();
1905
1906 builder.endSwitch(segmentBlocks);
1907
1908 return false;
1909}
1910
1911void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1912{
1913 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001914 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001915
1916 builder.clearAccessChain();
1917 builder.setAccessChainRValue(constant);
1918}
1919
1920bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1921{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001922 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001923 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001924 // Spec requires back edges to target header blocks, and every header block
1925 // must dominate its merge block. Make a header block first to ensure these
1926 // conditions are met. By definition, it will contain OpLoopMerge, followed
1927 // by a block-ending branch. But we don't want to put any other body/test
1928 // instructions in it, since the body/test may have arbitrary instructions,
1929 // including merges of its own.
1930 builder.setBuildPoint(&blocks.head);
1931 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001932 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001933 spv::Block& test = builder.makeNewBlock();
1934 builder.createBranch(&test);
1935
1936 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001937 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001938 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001939 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001940 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1941
1942 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001943 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001944 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001945 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001946 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001947 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001948
1949 builder.setBuildPoint(&blocks.continue_target);
1950 if (node->getTerminal())
1951 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001952 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001953 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001954 builder.createBranch(&blocks.body);
1955
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001956 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001957 builder.setBuildPoint(&blocks.body);
1958 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001959 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001960 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001961 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001962
1963 builder.setBuildPoint(&blocks.continue_target);
1964 if (node->getTerminal())
1965 node->getTerminal()->traverse(this);
1966 if (node->getTest()) {
1967 node->getTest()->traverse(this);
1968 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001969 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001970 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001971 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001972 // TODO: unless there was a break/return/discard instruction
1973 // somewhere in the body, this is an infinite loop, so we should
1974 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001975 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 }
John Kessenich140f3df2015-06-26 16:58:36 -06001977 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001978 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001979 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001980 return false;
1981}
1982
1983bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1984{
1985 if (node->getExpression())
1986 node->getExpression()->traverse(this);
1987
1988 switch (node->getFlowOp()) {
1989 case glslang::EOpKill:
1990 builder.makeDiscard();
1991 break;
1992 case glslang::EOpBreak:
1993 if (breakForLoop.top())
1994 builder.createLoopExit();
1995 else
1996 builder.addSwitchBreak();
1997 break;
1998 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001999 builder.createLoopContinue();
2000 break;
2001 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002002 if (node->getExpression()) {
2003 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2004 spv::Id returnId = accessChainLoad(glslangReturnType);
2005 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2006 builder.clearAccessChain();
2007 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2008 builder.setAccessChainLValue(copyId);
2009 multiTypeStore(glslangReturnType, returnId);
2010 returnId = builder.createLoad(copyId);
2011 }
2012 builder.makeReturn(false, returnId);
2013 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002014 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002015
2016 builder.clearAccessChain();
2017 break;
2018
2019 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002020 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002021 break;
2022 }
2023
2024 return false;
2025}
2026
2027spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2028{
qining25262b32016-05-06 17:25:16 -04002029 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002030 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002031 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002032 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002033 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002034 }
2035
2036 // Now, handle actual variables
2037 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2038 spv::Id spvType = convertGlslangToSpvType(node->getType());
2039
2040 const char* name = node->getName().c_str();
2041 if (glslang::IsAnonymous(name))
2042 name = "";
2043
2044 return builder.createVariable(storageClass, spvType, name);
2045}
2046
2047// Return type Id of the sampled type.
2048spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2049{
2050 switch (sampler.type) {
2051 case glslang::EbtFloat: return builder.makeFloatType(32);
2052 case glslang::EbtInt: return builder.makeIntType(32);
2053 case glslang::EbtUint: return builder.makeUintType(32);
2054 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002055 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 return builder.makeFloatType(32);
2057 }
2058}
2059
John Kessenich8c8505c2016-07-26 12:50:38 -06002060// If node is a swizzle operation, return the type that should be used if
2061// the swizzle base is first consumed by another operation, before the swizzle
2062// is applied.
2063spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2064{
John Kessenichecba76f2017-01-06 00:34:48 -07002065 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002066 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2067 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2068 else
2069 return spv::NoType;
2070}
2071
2072// When inverting a swizzle with a parent op, this function
2073// will apply the swizzle operation to a completed parent operation.
2074spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2075{
2076 std::vector<unsigned> swizzle;
2077 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2078 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2079}
2080
John Kessenich8c8505c2016-07-26 12:50:38 -06002081// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2082void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2083{
2084 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2085 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2086 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2087}
2088
John Kessenich3ac051e2015-12-20 11:29:16 -07002089// Convert from a glslang type to an SPV type, by calling into a
2090// recursive version of this function. This establishes the inherited
2091// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002092spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2093{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002094 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002095}
2096
2097// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002098// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002099// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002100spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002101{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002102 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002103
2104 switch (type.getBasicType()) {
2105 case glslang::EbtVoid:
2106 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002107 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002108 break;
2109 case glslang::EbtFloat:
2110 spvType = builder.makeFloatType(32);
2111 break;
2112 case glslang::EbtDouble:
2113 spvType = builder.makeFloatType(64);
2114 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002115#ifdef AMD_EXTENSIONS
2116 case glslang::EbtFloat16:
2117 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002118 spvType = builder.makeFloatType(16);
2119 break;
2120#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002121 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002122 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2123 // a 32-bit int where non-0 means true.
2124 if (explicitLayout != glslang::ElpNone)
2125 spvType = builder.makeUintType(32);
2126 else
2127 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002128 break;
2129 case glslang::EbtInt:
2130 spvType = builder.makeIntType(32);
2131 break;
2132 case glslang::EbtUint:
2133 spvType = builder.makeUintType(32);
2134 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002135 case glslang::EbtInt64:
2136 builder.addCapability(spv::CapabilityInt64);
2137 spvType = builder.makeIntType(64);
2138 break;
2139 case glslang::EbtUint64:
2140 builder.addCapability(spv::CapabilityInt64);
2141 spvType = builder.makeUintType(64);
2142 break;
John Kessenich426394d2015-07-23 10:22:48 -06002143 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002144 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002145 spvType = builder.makeUintType(32);
2146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002147 case glslang::EbtSampler:
2148 {
2149 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002150 if (sampler.sampler) {
2151 // pure sampler
2152 spvType = builder.makeSamplerType();
2153 } else {
2154 // an image is present, make its type
2155 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2156 sampler.image ? 2 : 1, TranslateImageFormat(type));
2157 if (sampler.combined) {
2158 // already has both image and sampler, make the combined type
2159 spvType = builder.makeSampledImageType(spvType);
2160 }
John Kessenich55e7d112015-11-15 21:33:39 -07002161 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002162 }
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164 case glslang::EbtStruct:
2165 case glslang::EbtBlock:
2166 {
2167 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002168 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002169
2170 // Try to share structs for different layouts, but not yet for other
2171 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002172 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002173 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002174 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002175 break;
2176
2177 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002178 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002179 memberRemapper[glslangMembers].resize(glslangMembers->size());
2180 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002181 }
2182 break;
2183 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002184 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002185 break;
2186 }
2187
2188 if (type.isMatrix())
2189 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2190 else {
2191 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2192 if (type.getVectorSize() > 1)
2193 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2194 }
2195
2196 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002197 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2198
John Kessenichc9a80832015-09-12 12:17:44 -06002199 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002200 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002201 // We need to decorate array strides for types needing explicit layout, except blocks.
2202 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002203 // Use a dummy glslang type for querying internal strides of
2204 // arrays of arrays, but using just a one-dimensional array.
2205 glslang::TType simpleArrayType(type, 0); // deference type of the array
2206 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2207 simpleArrayType.getArraySizes().dereference();
2208
2209 // Will compute the higher-order strides here, rather than making a whole
2210 // pile of types and doing repetitive recursion on their contents.
2211 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2212 }
John Kessenichf8842e52016-01-04 19:22:56 -07002213
2214 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002215 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002216 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002217 if (stride > 0)
2218 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002219 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002220 }
2221 } else {
2222 // single-dimensional array, and don't yet have stride
2223
John Kessenichf8842e52016-01-04 19:22:56 -07002224 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002225 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2226 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002227 }
John Kessenich31ed4832015-09-09 17:51:38 -06002228
John Kessenichc9a80832015-09-12 12:17:44 -06002229 // Do the outer dimension, which might not be known for a runtime-sized array
2230 if (type.isRuntimeSizedArray()) {
2231 spvType = builder.makeRuntimeArray(spvType);
2232 } else {
2233 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002234 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002235 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002236 if (stride > 0)
2237 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002238 }
2239
2240 return spvType;
2241}
2242
John Kessenich6090df02016-06-30 21:18:02 -06002243// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2244// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2245// Mutually recursive with convertGlslangToSpvType().
2246spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2247 const glslang::TTypeList* glslangMembers,
2248 glslang::TLayoutPacking explicitLayout,
2249 const glslang::TQualifier& qualifier)
2250{
2251 // Create a vector of struct types for SPIR-V to consume
2252 std::vector<spv::Id> spvMembers;
2253 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2254 int locationOffset = 0; // for use across struct members, when they are called recursively
2255 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2256 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2257 if (glslangMember.hiddenMember()) {
2258 ++memberDelta;
2259 if (type.getBasicType() == glslang::EbtBlock)
2260 memberRemapper[glslangMembers][i] = -1;
2261 } else {
2262 if (type.getBasicType() == glslang::EbtBlock)
2263 memberRemapper[glslangMembers][i] = i - memberDelta;
2264 // modify just this child's view of the qualifier
2265 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2266 InheritQualifiers(memberQualifier, qualifier);
2267
2268 // manually inherit location; it's more complex
2269 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2270 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2271 if (qualifier.hasLocation())
2272 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2273
2274 // recurse
2275 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2276 }
2277 }
2278
2279 // Make the SPIR-V type
2280 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002281 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002282 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2283
2284 // Decorate it
2285 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2286
2287 return spvType;
2288}
2289
2290void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2291 const glslang::TTypeList* glslangMembers,
2292 glslang::TLayoutPacking explicitLayout,
2293 const glslang::TQualifier& qualifier,
2294 spv::Id spvType)
2295{
2296 // Name and decorate the non-hidden members
2297 int offset = -1;
2298 int locationOffset = 0; // for use within the members of this struct
2299 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2300 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2301 int member = i;
2302 if (type.getBasicType() == glslang::EbtBlock)
2303 member = memberRemapper[glslangMembers][i];
2304
2305 // modify just this child's view of the qualifier
2306 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2307 InheritQualifiers(memberQualifier, qualifier);
2308
2309 // using -1 above to indicate a hidden member
2310 if (member >= 0) {
2311 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2312 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2313 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2314 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002315 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2316 type.getQualifier().storage == glslang::EvqVaryingOut) {
2317 if (type.getBasicType() == glslang::EbtBlock ||
2318 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002319 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2320 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2321 }
2322 }
2323 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2324
2325 if (qualifier.storage == glslang::EvqBuffer) {
2326 std::vector<spv::Decoration> memory;
2327 TranslateMemoryDecoration(memberQualifier, memory);
2328 for (unsigned int i = 0; i < memory.size(); ++i)
2329 addMemberDecoration(spvType, member, memory[i]);
2330 }
2331
John Kessenich2f47bc92016-06-30 21:47:35 -06002332 // Compute location decoration; tricky based on whether inheritance is at play and
2333 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002334 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2335 // probably move to the linker stage of the front end proper, and just have the
2336 // answer sitting already distributed throughout the individual member locations.
2337 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002338 // Ignore member locations if the container is an array, as that's
2339 // ill-specified and decisions have been made to not allow this anyway.
2340 // The object itself must have a location, and that comes out from decorating the object,
2341 // not the type (this code decorates types).
2342 if (! type.isArray()) {
2343 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2344 // struct members should not have explicit locations
2345 assert(type.getBasicType() != glslang::EbtStruct);
2346 location = memberQualifier.layoutLocation;
2347 } else if (type.getBasicType() != glslang::EbtBlock) {
2348 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2349 // The members, and their nested types, must not themselves have Location decorations.
2350 } else if (qualifier.hasLocation()) // inheritance
2351 location = qualifier.layoutLocation + locationOffset;
2352 }
John Kessenich6090df02016-06-30 21:18:02 -06002353 if (location >= 0)
2354 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2355
John Kessenich2f47bc92016-06-30 21:47:35 -06002356 if (qualifier.hasLocation()) // track for upcoming inheritance
2357 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2358
John Kessenich6090df02016-06-30 21:18:02 -06002359 // component, XFB, others
2360 if (glslangMember.getQualifier().hasComponent())
2361 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2362 if (glslangMember.getQualifier().hasXfbOffset())
2363 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2364 else if (explicitLayout != glslang::ElpNone) {
2365 // figure out what to do with offset, which is accumulating
2366 int nextOffset;
2367 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2368 if (offset >= 0)
2369 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2370 offset = nextOffset;
2371 }
2372
2373 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2374 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2375
2376 // built-in variable decorations
2377 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002378 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002379 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002380
2381#ifdef NV_EXTENSIONS
2382 if (builtIn == spv::BuiltInLayer) {
2383 // SPV_NV_viewport_array2 extension
2384 if (glslangMember.getQualifier().layoutViewportRelative){
2385 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2386 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2387 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2388 }
2389 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2390 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2391 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2392 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2393 }
2394 }
chaocdf3956c2017-02-14 14:52:34 -08002395 if (glslangMember.getQualifier().layoutPassthrough) {
2396 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2397 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2398 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2399 }
chaoc771d89f2017-01-13 01:10:53 -08002400#endif
John Kessenich6090df02016-06-30 21:18:02 -06002401 }
2402 }
2403
2404 // Decorate the structure
2405 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2406 addDecoration(spvType, TranslateBlockDecoration(type));
2407 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2408 builder.addCapability(spv::CapabilityGeometryStreams);
2409 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2410 }
2411 if (glslangIntermediate->getXfbMode()) {
2412 builder.addCapability(spv::CapabilityTransformFeedback);
2413 if (type.getQualifier().hasXfbStride())
2414 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2415 if (type.getQualifier().hasXfbBuffer())
2416 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2417 }
2418}
2419
John Kessenich6c292d32016-02-15 20:58:50 -07002420// Turn the expression forming the array size into an id.
2421// This is not quite trivial, because of specialization constants.
2422// Sometimes, a raw constant is turned into an Id, and sometimes
2423// a specialization constant expression is.
2424spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2425{
2426 // First, see if this is sized with a node, meaning a specialization constant:
2427 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2428 if (specNode != nullptr) {
2429 builder.clearAccessChain();
2430 specNode->traverse(this);
2431 return accessChainLoad(specNode->getAsTyped()->getType());
2432 }
qining25262b32016-05-06 17:25:16 -04002433
John Kessenich6c292d32016-02-15 20:58:50 -07002434 // Otherwise, need a compile-time (front end) size, get it:
2435 int size = arraySizes.getDimSize(dim);
2436 assert(size > 0);
2437 return builder.makeUintConstant(size);
2438}
2439
John Kessenich103bef92016-02-08 21:38:15 -07002440// Wrap the builder's accessChainLoad to:
2441// - localize handling of RelaxedPrecision
2442// - use the SPIR-V inferred type instead of another conversion of the glslang type
2443// (avoids unnecessary work and possible type punning for structures)
2444// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002445spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2446{
John Kessenich103bef92016-02-08 21:38:15 -07002447 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2448 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2449
2450 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002451 if (type.getBasicType() == glslang::EbtBool) {
2452 if (builder.isScalarType(nominalTypeId)) {
2453 // Conversion for bool
2454 spv::Id boolType = builder.makeBoolType();
2455 if (nominalTypeId != boolType)
2456 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2457 } else if (builder.isVectorType(nominalTypeId)) {
2458 // Conversion for bvec
2459 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2460 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2461 if (nominalTypeId != bvecType)
2462 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2463 }
2464 }
John Kessenich103bef92016-02-08 21:38:15 -07002465
2466 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002467}
2468
Rex Xu27253232016-02-23 17:51:09 +08002469// Wrap the builder's accessChainStore to:
2470// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002471//
2472// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002473void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2474{
2475 // Need to convert to abstract types when necessary
2476 if (type.getBasicType() == glslang::EbtBool) {
2477 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2478
2479 if (builder.isScalarType(nominalTypeId)) {
2480 // Conversion for bool
2481 spv::Id boolType = builder.makeBoolType();
2482 if (nominalTypeId != boolType) {
2483 spv::Id zero = builder.makeUintConstant(0);
2484 spv::Id one = builder.makeUintConstant(1);
2485 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2486 }
2487 } else if (builder.isVectorType(nominalTypeId)) {
2488 // Conversion for bvec
2489 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2490 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2491 if (nominalTypeId != bvecType) {
2492 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2493 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2494 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2495 }
2496 }
2497 }
2498
2499 builder.accessChainStore(rvalue);
2500}
2501
John Kessenich4bf71552016-09-02 11:20:21 -06002502// For storing when types match at the glslang level, but not might match at the
2503// SPIR-V level.
2504//
2505// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002506// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002507// as in a member-decorated way.
2508//
2509// NOTE: This function can handle any store request; if it's not special it
2510// simplifies to a simple OpStore.
2511//
2512// Implicitly uses the existing builder.accessChain as the storage target.
2513void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2514{
John Kessenichb3e24e42016-09-11 12:33:43 -06002515 // we only do the complex path here if it's an aggregate
2516 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002517 accessChainStore(type, rValue);
2518 return;
2519 }
2520
John Kessenichb3e24e42016-09-11 12:33:43 -06002521 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002522 spv::Id rType = builder.getTypeId(rValue);
2523 spv::Id lValue = builder.accessChainGetLValue();
2524 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2525 if (lType == rType) {
2526 accessChainStore(type, rValue);
2527 return;
2528 }
2529
John Kessenichb3e24e42016-09-11 12:33:43 -06002530 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002531 // where the two types were the same type in GLSL. This requires member
2532 // by member copy, recursively.
2533
John Kessenichb3e24e42016-09-11 12:33:43 -06002534 // If an array, copy element by element.
2535 if (type.isArray()) {
2536 glslang::TType glslangElementType(type, 0);
2537 spv::Id elementRType = builder.getContainedTypeId(rType);
2538 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2539 // get the source member
2540 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002541
John Kessenichb3e24e42016-09-11 12:33:43 -06002542 // set up the target storage
2543 builder.clearAccessChain();
2544 builder.setAccessChainLValue(lValue);
2545 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002546
John Kessenichb3e24e42016-09-11 12:33:43 -06002547 // store the member
2548 multiTypeStore(glslangElementType, elementRValue);
2549 }
2550 } else {
2551 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002552
John Kessenichb3e24e42016-09-11 12:33:43 -06002553 // loop over structure members
2554 const glslang::TTypeList& members = *type.getStruct();
2555 for (int m = 0; m < (int)members.size(); ++m) {
2556 const glslang::TType& glslangMemberType = *members[m].type;
2557
2558 // get the source member
2559 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2560 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2561
2562 // set up the target storage
2563 builder.clearAccessChain();
2564 builder.setAccessChainLValue(lValue);
2565 builder.accessChainPush(builder.makeIntConstant(m));
2566
2567 // store the member
2568 multiTypeStore(glslangMemberType, memberRValue);
2569 }
John Kessenich4bf71552016-09-02 11:20:21 -06002570 }
2571}
2572
John Kessenichf85e8062015-12-19 13:57:10 -07002573// Decide whether or not this type should be
2574// decorated with offsets and strides, and if so
2575// whether std140 or std430 rules should be applied.
2576glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002577{
John Kessenichf85e8062015-12-19 13:57:10 -07002578 // has to be a block
2579 if (type.getBasicType() != glslang::EbtBlock)
2580 return glslang::ElpNone;
2581
2582 // has to be a uniform or buffer block
2583 if (type.getQualifier().storage != glslang::EvqUniform &&
2584 type.getQualifier().storage != glslang::EvqBuffer)
2585 return glslang::ElpNone;
2586
2587 // return the layout to use
2588 switch (type.getQualifier().layoutPacking) {
2589 case glslang::ElpStd140:
2590 case glslang::ElpStd430:
2591 return type.getQualifier().layoutPacking;
2592 default:
2593 return glslang::ElpNone;
2594 }
John Kessenich31ed4832015-09-09 17:51:38 -06002595}
2596
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002597// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002598int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002599{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002600 int size;
John Kessenich49987892015-12-29 17:11:44 -07002601 int stride;
2602 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002603
2604 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002605}
2606
John Kessenich49987892015-12-29 17:11:44 -07002607// 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 -07002608// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002609int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002610{
John Kessenich49987892015-12-29 17:11:44 -07002611 glslang::TType elementType;
2612 elementType.shallowCopy(matrixType);
2613 elementType.clearArraySizes();
2614
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002615 int size;
John Kessenich49987892015-12-29 17:11:44 -07002616 int stride;
2617 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2618
2619 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002620}
2621
John Kessenich5e4b1242015-08-06 22:53:06 -06002622// Given a member type of a struct, realign the current offset for it, and compute
2623// the next (not yet aligned) offset for the next member, which will get aligned
2624// on the next call.
2625// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2626// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2627// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002628void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002629 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002630{
2631 // this will get a positive value when deemed necessary
2632 nextOffset = -1;
2633
John Kessenich5e4b1242015-08-06 22:53:06 -06002634 // override anything in currentOffset with user-set offset
2635 if (memberType.getQualifier().hasOffset())
2636 currentOffset = memberType.getQualifier().layoutOffset;
2637
2638 // It could be that current linker usage in glslang updated all the layoutOffset,
2639 // in which case the following code does not matter. But, that's not quite right
2640 // once cross-compilation unit GLSL validation is done, as the original user
2641 // settings are needed in layoutOffset, and then the following will come into play.
2642
John Kessenichf85e8062015-12-19 13:57:10 -07002643 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002644 if (! memberType.getQualifier().hasOffset())
2645 currentOffset = -1;
2646
2647 return;
2648 }
2649
John Kessenichf85e8062015-12-19 13:57:10 -07002650 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002651 if (currentOffset < 0)
2652 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002653
John Kessenich5e4b1242015-08-06 22:53:06 -06002654 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2655 // but possibly not yet correctly aligned.
2656
2657 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002658 int dummyStride;
2659 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002660 glslang::RoundToPow2(currentOffset, memberAlignment);
2661 nextOffset = currentOffset + memberSize;
2662}
2663
David Netoa901ffe2016-06-08 14:11:40 +01002664void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002665{
David Netoa901ffe2016-06-08 14:11:40 +01002666 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2667 switch (glslangBuiltIn)
2668 {
2669 case glslang::EbvClipDistance:
2670 case glslang::EbvCullDistance:
2671 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002672#ifdef NV_EXTENSIONS
2673 case glslang::EbvLayer:
2674 case glslang::EbvViewportMaskNV:
2675 case glslang::EbvSecondaryPositionNV:
2676 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002677 case glslang::EbvPositionPerViewNV:
2678 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002679#endif
David Netoa901ffe2016-06-08 14:11:40 +01002680 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2681 // Alternately, we could just call this for any glslang built-in, since the
2682 // capability already guards against duplicates.
2683 TranslateBuiltInDecoration(glslangBuiltIn, false);
2684 break;
2685 default:
2686 // Capabilities were already generated when the struct was declared.
2687 break;
2688 }
John Kessenichebb50532016-05-16 19:22:05 -06002689}
2690
John Kessenich6fccb3c2016-09-19 16:01:41 -06002691bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002692{
John Kessenicheee9d532016-09-19 18:09:30 -06002693 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002694}
2695
2696// Make all the functions, skeletally, without actually visiting their bodies.
2697void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2698{
2699 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2700 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002701 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002702 continue;
2703
2704 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002705 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002706 //
qining25262b32016-05-06 17:25:16 -04002707 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002708 // function. What it is an address of varies:
2709 //
John Kessenich4bf71552016-09-02 11:20:21 -06002710 // - "in" parameters not marked as "const" can be written to without modifying the calling
2711 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002712 //
2713 // - "const in" parameters can just be the r-value, as no writes need occur.
2714 //
John Kessenich4bf71552016-09-02 11:20:21 -06002715 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2716 // 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 -06002717
2718 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002719 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002720 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2721
2722 for (int p = 0; p < (int)parameters.size(); ++p) {
2723 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2724 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002725 if (paramType.isOpaque())
2726 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2727 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002728 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2729 else
John Kessenich4bf71552016-09-02 11:20:21 -06002730 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002731 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002732 paramTypes.push_back(typeId);
2733 }
2734
2735 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002736 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2737 convertGlslangToSpvType(glslFunction->getType()),
2738 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002739
2740 // Track function to emit/call later
2741 functionMap[glslFunction->getName().c_str()] = function;
2742
2743 // Set the parameter id's
2744 for (int p = 0; p < (int)parameters.size(); ++p) {
2745 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2746 // give a name too
2747 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2748 }
2749 }
2750}
2751
2752// Process all the initializers, while skipping the functions and link objects
2753void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2754{
2755 builder.setBuildPoint(shaderEntry->getLastBlock());
2756 for (int i = 0; i < (int)initializers.size(); ++i) {
2757 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2758 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2759
2760 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002761 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002762 initializer->traverse(this);
2763 }
2764 }
2765}
2766
2767// Process all the functions, while skipping initializers.
2768void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2769{
2770 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2771 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002772 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002773 node->traverse(this);
2774 }
2775}
2776
2777void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2778{
qining25262b32016-05-06 17:25:16 -04002779 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002780 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002781 currentFunction = functionMap[node->getName().c_str()];
2782 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002783 builder.setBuildPoint(functionBlock);
2784}
2785
Rex Xu04db3f52015-09-16 11:44:02 +08002786void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002787{
Rex Xufc618912015-09-09 16:42:49 +08002788 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002789
2790 glslang::TSampler sampler = {};
2791 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002792 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002793 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2794 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2795 }
2796
John Kessenich140f3df2015-06-26 16:58:36 -06002797 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2798 builder.clearAccessChain();
2799 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002800
2801 // Special case l-value operands
2802 bool lvalue = false;
2803 switch (node.getOp()) {
2804 case glslang::EOpImageAtomicAdd:
2805 case glslang::EOpImageAtomicMin:
2806 case glslang::EOpImageAtomicMax:
2807 case glslang::EOpImageAtomicAnd:
2808 case glslang::EOpImageAtomicOr:
2809 case glslang::EOpImageAtomicXor:
2810 case glslang::EOpImageAtomicExchange:
2811 case glslang::EOpImageAtomicCompSwap:
2812 if (i == 0)
2813 lvalue = true;
2814 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002815 case glslang::EOpSparseImageLoad:
2816 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2817 lvalue = true;
2818 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002819 case glslang::EOpSparseTexture:
2820 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2821 lvalue = true;
2822 break;
2823 case glslang::EOpSparseTextureClamp:
2824 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2825 lvalue = true;
2826 break;
2827 case glslang::EOpSparseTextureLod:
2828 case glslang::EOpSparseTextureOffset:
2829 if (i == 3)
2830 lvalue = true;
2831 break;
2832 case glslang::EOpSparseTextureFetch:
2833 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2834 lvalue = true;
2835 break;
2836 case glslang::EOpSparseTextureFetchOffset:
2837 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2838 lvalue = true;
2839 break;
2840 case glslang::EOpSparseTextureLodOffset:
2841 case glslang::EOpSparseTextureGrad:
2842 case glslang::EOpSparseTextureOffsetClamp:
2843 if (i == 4)
2844 lvalue = true;
2845 break;
2846 case glslang::EOpSparseTextureGradOffset:
2847 case glslang::EOpSparseTextureGradClamp:
2848 if (i == 5)
2849 lvalue = true;
2850 break;
2851 case glslang::EOpSparseTextureGradOffsetClamp:
2852 if (i == 6)
2853 lvalue = true;
2854 break;
2855 case glslang::EOpSparseTextureGather:
2856 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2857 lvalue = true;
2858 break;
2859 case glslang::EOpSparseTextureGatherOffset:
2860 case glslang::EOpSparseTextureGatherOffsets:
2861 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2862 lvalue = true;
2863 break;
Rex Xufc618912015-09-09 16:42:49 +08002864 default:
2865 break;
2866 }
2867
Rex Xu6b86d492015-09-16 17:48:22 +08002868 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002869 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002870 else
John Kessenich32cfd492016-02-02 12:37:46 -07002871 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002872 }
2873}
2874
John Kessenichfc51d282015-08-19 13:34:18 -06002875void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002876{
John Kessenichfc51d282015-08-19 13:34:18 -06002877 builder.clearAccessChain();
2878 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002879 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002880}
John Kessenich140f3df2015-06-26 16:58:36 -06002881
John Kessenichfc51d282015-08-19 13:34:18 -06002882spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2883{
Rex Xufc618912015-09-09 16:42:49 +08002884 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002885 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002886 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002887 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002888
John Kessenichfc51d282015-08-19 13:34:18 -06002889 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002890 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2891 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2892 std::vector<spv::Id> arguments;
2893 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002894 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002895 else
2896 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002897 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002898
2899 spv::Builder::TextureParameters params = { };
2900 params.sampler = arguments[0];
2901
Rex Xu04db3f52015-09-16 11:44:02 +08002902 glslang::TCrackedTextureOp cracked;
2903 node->crackTexture(sampler, cracked);
2904
John Kessenichfc51d282015-08-19 13:34:18 -06002905 // Check for queries
2906 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002907 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2908 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002909 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002910
John Kessenichfc51d282015-08-19 13:34:18 -06002911 switch (node->getOp()) {
2912 case glslang::EOpImageQuerySize:
2913 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002914 if (arguments.size() > 1) {
2915 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002916 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002917 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002919 case glslang::EOpImageQuerySamples:
2920 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002922 case glslang::EOpTextureQueryLod:
2923 params.coords = arguments[1];
2924 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2925 case glslang::EOpTextureQueryLevels:
2926 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002927 case glslang::EOpSparseTexelsResident:
2928 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002929 default:
2930 assert(0);
2931 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002932 }
John Kessenich140f3df2015-06-26 16:58:36 -06002933 }
2934
Rex Xufc618912015-09-09 16:42:49 +08002935 // Check for image functions other than queries
2936 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002937 std::vector<spv::Id> operands;
2938 auto opIt = arguments.begin();
2939 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002940
2941 // Handle subpass operations
2942 // TODO: GLSL should change to have the "MS" only on the type rather than the
2943 // built-in function.
2944 if (cracked.subpass) {
2945 // add on the (0,0) coordinate
2946 spv::Id zero = builder.makeIntConstant(0);
2947 std::vector<spv::Id> comps;
2948 comps.push_back(zero);
2949 comps.push_back(zero);
2950 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2951 if (sampler.ms) {
2952 operands.push_back(spv::ImageOperandsSampleMask);
2953 operands.push_back(*(opIt++));
2954 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002955 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002956 }
2957
John Kessenich56bab042015-09-16 10:54:31 -06002958 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002959 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002960 if (sampler.ms) {
2961 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002962 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002963 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002964 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2965 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002966 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002967 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002968 if (sampler.ms) {
2969 operands.push_back(*(opIt + 1));
2970 operands.push_back(spv::ImageOperandsSampleMask);
2971 operands.push_back(*opIt);
2972 } else
2973 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002974 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002975 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2976 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002977 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002978 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2979 builder.addCapability(spv::CapabilitySparseResidency);
2980 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2981 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2982
2983 if (sampler.ms) {
2984 operands.push_back(spv::ImageOperandsSampleMask);
2985 operands.push_back(*opIt++);
2986 }
2987
2988 // Create the return type that was a special structure
2989 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002990 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002991 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2992 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2993
2994 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2995
2996 // Decode the return type
2997 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2998 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002999 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003000 // Process image atomic operations
3001
3002 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3003 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003004 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003005
John Kessenich8c8505c2016-07-26 12:50:38 -06003006 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003007 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003008
3009 std::vector<spv::Id> operands;
3010 operands.push_back(pointer);
3011 for (; opIt != arguments.end(); ++opIt)
3012 operands.push_back(*opIt);
3013
John Kessenich8c8505c2016-07-26 12:50:38 -06003014 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003015 }
3016 }
3017
3018 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003019 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003020 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3021
John Kessenichfc51d282015-08-19 13:34:18 -06003022 // check for bias argument
3023 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003024 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003025 int nonBiasArgCount = 2;
3026 if (cracked.offset)
3027 ++nonBiasArgCount;
3028 if (cracked.grad)
3029 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003030 if (cracked.lodClamp)
3031 ++nonBiasArgCount;
3032 if (sparse)
3033 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003034
3035 if ((int)arguments.size() > nonBiasArgCount)
3036 bias = true;
3037 }
3038
John Kessenicha5c33d62016-06-02 23:45:21 -06003039 // See if the sampler param should really be just the SPV image part
3040 if (cracked.fetch) {
3041 // a fetch needs to have the image extracted first
3042 if (builder.isSampledImage(params.sampler))
3043 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3044 }
3045
John Kessenichfc51d282015-08-19 13:34:18 -06003046 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003047
John Kessenichfc51d282015-08-19 13:34:18 -06003048 params.coords = arguments[1];
3049 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003050 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003051
3052 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003053 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003054 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003055 ++extraArgs;
3056 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003057 params.Dref = arguments[2];
3058 ++extraArgs;
3059 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003060 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003061 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003062 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003063 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003064 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003065 dRefComp = builder.getNumComponents(params.coords) - 1;
3066 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003067 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3068 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003069
3070 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003071 if (cracked.lod) {
3072 params.lod = arguments[2];
3073 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003074 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3075 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3076 noImplicitLod = true;
3077 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003078
3079 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003080 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003081 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003082 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003083 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003084
3085 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003086 if (cracked.grad) {
3087 params.gradX = arguments[2 + extraArgs];
3088 params.gradY = arguments[3 + extraArgs];
3089 extraArgs += 2;
3090 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003091
3092 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003093 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003094 params.offset = arguments[2 + extraArgs];
3095 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003096 } else if (cracked.offsets) {
3097 params.offsets = arguments[2 + extraArgs];
3098 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003099 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003100
3101 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003102 if (cracked.lodClamp) {
3103 params.lodClamp = arguments[2 + extraArgs];
3104 ++extraArgs;
3105 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003106
3107 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003108 if (sparse) {
3109 params.texelOut = arguments[2 + extraArgs];
3110 ++extraArgs;
3111 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003112
3113 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003114 if (bias) {
3115 params.bias = arguments[2 + extraArgs];
3116 ++extraArgs;
3117 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003118
3119 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003120 if (cracked.gather && ! sampler.shadow) {
3121 // default component is 0, if missing, otherwise an argument
3122 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003123 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003124 ++extraArgs;
3125 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003126 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003127 }
3128 }
John Kessenichfc51d282015-08-19 13:34:18 -06003129
John Kessenich65336482016-06-16 14:06:26 -06003130 // projective component (might not to move)
3131 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3132 // are divided by the last component of P."
3133 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3134 // unused components will appear after all used components."
3135 if (cracked.proj) {
3136 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3137 int projTargetComp;
3138 switch (sampler.dim) {
3139 case glslang::Esd1D: projTargetComp = 1; break;
3140 case glslang::Esd2D: projTargetComp = 2; break;
3141 case glslang::EsdRect: projTargetComp = 2; break;
3142 default: projTargetComp = projSourceComp; break;
3143 }
3144 // copy the projective coordinate if we have to
3145 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003146 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003147 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3148 projSourceComp);
3149 params.coords = builder.createCompositeInsert(projComp, params.coords,
3150 builder.getTypeId(params.coords), projTargetComp);
3151 }
3152 }
3153
John Kessenich8c8505c2016-07-26 12:50:38 -06003154 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003155}
3156
3157spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3158{
3159 // Grab the function's pointer from the previously created function
3160 spv::Function* function = functionMap[node->getName().c_str()];
3161 if (! function)
3162 return 0;
3163
3164 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3165 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3166
3167 // See comments in makeFunctions() for details about the semantics for parameter passing.
3168 //
3169 // These imply we need a four step process:
3170 // 1. Evaluate the arguments
3171 // 2. Allocate and make copies of in, out, and inout arguments
3172 // 3. Make the call
3173 // 4. Copy back the results
3174
3175 // 1. Evaluate the arguments
3176 std::vector<spv::Builder::AccessChain> lValues;
3177 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003178 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003179 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003180 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003181 // build l-value
3182 builder.clearAccessChain();
3183 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003184 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003185 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003186 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003187 // save l-value
3188 lValues.push_back(builder.getAccessChain());
3189 } else {
3190 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003191 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003192 }
3193 }
3194
3195 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3196 // copy the original into that space.
3197 //
3198 // Also, build up the list of actual arguments to pass in for the call
3199 int lValueCount = 0;
3200 int rValueCount = 0;
3201 std::vector<spv::Id> spvArgs;
3202 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003203 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003204 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003205 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003206 builder.setAccessChain(lValues[lValueCount]);
3207 arg = builder.accessChainGetLValue();
3208 ++lValueCount;
3209 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003210 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003211 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3212 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3213 // need to copy the input into output space
3214 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003215 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003216 builder.clearAccessChain();
3217 builder.setAccessChainLValue(arg);
3218 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003219 }
3220 ++lValueCount;
3221 } else {
3222 arg = rValues[rValueCount];
3223 ++rValueCount;
3224 }
3225 spvArgs.push_back(arg);
3226 }
3227
3228 // 3. Make the call.
3229 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003230 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003231
3232 // 4. Copy back out an "out" arguments.
3233 lValueCount = 0;
3234 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003235 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003236 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3237 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3238 spv::Id copy = builder.createLoad(spvArgs[a]);
3239 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003240 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003241 }
3242 ++lValueCount;
3243 }
3244 }
3245
3246 return result;
3247}
3248
3249// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003250spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3251 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003252 spv::Id typeId, spv::Id left, spv::Id right,
3253 glslang::TBasicType typeProxy, bool reduceComparison)
3254{
Rex Xu8ff43de2016-04-22 16:51:45 +08003255 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003256#ifdef AMD_EXTENSIONS
3257 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3258#else
John Kessenich140f3df2015-06-26 16:58:36 -06003259 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003260#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003261 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003262
3263 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003264 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003265 bool comparison = false;
3266
3267 switch (op) {
3268 case glslang::EOpAdd:
3269 case glslang::EOpAddAssign:
3270 if (isFloat)
3271 binOp = spv::OpFAdd;
3272 else
3273 binOp = spv::OpIAdd;
3274 break;
3275 case glslang::EOpSub:
3276 case glslang::EOpSubAssign:
3277 if (isFloat)
3278 binOp = spv::OpFSub;
3279 else
3280 binOp = spv::OpISub;
3281 break;
3282 case glslang::EOpMul:
3283 case glslang::EOpMulAssign:
3284 if (isFloat)
3285 binOp = spv::OpFMul;
3286 else
3287 binOp = spv::OpIMul;
3288 break;
3289 case glslang::EOpVectorTimesScalar:
3290 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003291 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003292 if (builder.isVector(right))
3293 std::swap(left, right);
3294 assert(builder.isScalar(right));
3295 needMatchingVectors = false;
3296 binOp = spv::OpVectorTimesScalar;
3297 } else
3298 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003299 break;
3300 case glslang::EOpVectorTimesMatrix:
3301 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003302 binOp = spv::OpVectorTimesMatrix;
3303 break;
3304 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003305 binOp = spv::OpMatrixTimesVector;
3306 break;
3307 case glslang::EOpMatrixTimesScalar:
3308 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003309 binOp = spv::OpMatrixTimesScalar;
3310 break;
3311 case glslang::EOpMatrixTimesMatrix:
3312 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003313 binOp = spv::OpMatrixTimesMatrix;
3314 break;
3315 case glslang::EOpOuterProduct:
3316 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003317 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 break;
3319
3320 case glslang::EOpDiv:
3321 case glslang::EOpDivAssign:
3322 if (isFloat)
3323 binOp = spv::OpFDiv;
3324 else if (isUnsigned)
3325 binOp = spv::OpUDiv;
3326 else
3327 binOp = spv::OpSDiv;
3328 break;
3329 case glslang::EOpMod:
3330 case glslang::EOpModAssign:
3331 if (isFloat)
3332 binOp = spv::OpFMod;
3333 else if (isUnsigned)
3334 binOp = spv::OpUMod;
3335 else
3336 binOp = spv::OpSMod;
3337 break;
3338 case glslang::EOpRightShift:
3339 case glslang::EOpRightShiftAssign:
3340 if (isUnsigned)
3341 binOp = spv::OpShiftRightLogical;
3342 else
3343 binOp = spv::OpShiftRightArithmetic;
3344 break;
3345 case glslang::EOpLeftShift:
3346 case glslang::EOpLeftShiftAssign:
3347 binOp = spv::OpShiftLeftLogical;
3348 break;
3349 case glslang::EOpAnd:
3350 case glslang::EOpAndAssign:
3351 binOp = spv::OpBitwiseAnd;
3352 break;
3353 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003354 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003355 binOp = spv::OpLogicalAnd;
3356 break;
3357 case glslang::EOpInclusiveOr:
3358 case glslang::EOpInclusiveOrAssign:
3359 binOp = spv::OpBitwiseOr;
3360 break;
3361 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003362 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003363 binOp = spv::OpLogicalOr;
3364 break;
3365 case glslang::EOpExclusiveOr:
3366 case glslang::EOpExclusiveOrAssign:
3367 binOp = spv::OpBitwiseXor;
3368 break;
3369 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003370 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003371 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
3373
3374 case glslang::EOpLessThan:
3375 case glslang::EOpGreaterThan:
3376 case glslang::EOpLessThanEqual:
3377 case glslang::EOpGreaterThanEqual:
3378 case glslang::EOpEqual:
3379 case glslang::EOpNotEqual:
3380 case glslang::EOpVectorEqual:
3381 case glslang::EOpVectorNotEqual:
3382 comparison = true;
3383 break;
3384 default:
3385 break;
3386 }
3387
John Kessenich7c1aa102015-10-15 13:29:11 -06003388 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003389 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003390 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003391 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003392 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003393
3394 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003395 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003396 builder.promoteScalar(precision, left, right);
3397
qining25262b32016-05-06 17:25:16 -04003398 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3399 addDecoration(result, noContraction);
3400 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003401 }
3402
3403 if (! comparison)
3404 return 0;
3405
John Kessenich7c1aa102015-10-15 13:29:11 -06003406 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003407
John Kessenich4583b612016-08-07 19:14:22 -06003408 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3409 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003410 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003411
3412 switch (op) {
3413 case glslang::EOpLessThan:
3414 if (isFloat)
3415 binOp = spv::OpFOrdLessThan;
3416 else if (isUnsigned)
3417 binOp = spv::OpULessThan;
3418 else
3419 binOp = spv::OpSLessThan;
3420 break;
3421 case glslang::EOpGreaterThan:
3422 if (isFloat)
3423 binOp = spv::OpFOrdGreaterThan;
3424 else if (isUnsigned)
3425 binOp = spv::OpUGreaterThan;
3426 else
3427 binOp = spv::OpSGreaterThan;
3428 break;
3429 case glslang::EOpLessThanEqual:
3430 if (isFloat)
3431 binOp = spv::OpFOrdLessThanEqual;
3432 else if (isUnsigned)
3433 binOp = spv::OpULessThanEqual;
3434 else
3435 binOp = spv::OpSLessThanEqual;
3436 break;
3437 case glslang::EOpGreaterThanEqual:
3438 if (isFloat)
3439 binOp = spv::OpFOrdGreaterThanEqual;
3440 else if (isUnsigned)
3441 binOp = spv::OpUGreaterThanEqual;
3442 else
3443 binOp = spv::OpSGreaterThanEqual;
3444 break;
3445 case glslang::EOpEqual:
3446 case glslang::EOpVectorEqual:
3447 if (isFloat)
3448 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003449 else if (isBool)
3450 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003451 else
3452 binOp = spv::OpIEqual;
3453 break;
3454 case glslang::EOpNotEqual:
3455 case glslang::EOpVectorNotEqual:
3456 if (isFloat)
3457 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003458 else if (isBool)
3459 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003460 else
3461 binOp = spv::OpINotEqual;
3462 break;
3463 default:
3464 break;
3465 }
3466
qining25262b32016-05-06 17:25:16 -04003467 if (binOp != spv::OpNop) {
3468 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3469 addDecoration(result, noContraction);
3470 return builder.setPrecision(result, precision);
3471 }
John Kessenich140f3df2015-06-26 16:58:36 -06003472
3473 return 0;
3474}
3475
John Kessenich04bb8a02015-12-12 12:28:14 -07003476//
3477// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3478// These can be any of:
3479//
3480// matrix * scalar
3481// scalar * matrix
3482// matrix * matrix linear algebraic
3483// matrix * vector
3484// vector * matrix
3485// matrix * matrix componentwise
3486// matrix op matrix op in {+, -, /}
3487// matrix op scalar op in {+, -, /}
3488// scalar op matrix op in {+, -, /}
3489//
qining25262b32016-05-06 17:25:16 -04003490spv::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 -07003491{
3492 bool firstClass = true;
3493
3494 // First, handle first-class matrix operations (* and matrix/scalar)
3495 switch (op) {
3496 case spv::OpFDiv:
3497 if (builder.isMatrix(left) && builder.isScalar(right)) {
3498 // turn matrix / scalar into a multiply...
3499 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3500 op = spv::OpMatrixTimesScalar;
3501 } else
3502 firstClass = false;
3503 break;
3504 case spv::OpMatrixTimesScalar:
3505 if (builder.isMatrix(right))
3506 std::swap(left, right);
3507 assert(builder.isScalar(right));
3508 break;
3509 case spv::OpVectorTimesMatrix:
3510 assert(builder.isVector(left));
3511 assert(builder.isMatrix(right));
3512 break;
3513 case spv::OpMatrixTimesVector:
3514 assert(builder.isMatrix(left));
3515 assert(builder.isVector(right));
3516 break;
3517 case spv::OpMatrixTimesMatrix:
3518 assert(builder.isMatrix(left));
3519 assert(builder.isMatrix(right));
3520 break;
3521 default:
3522 firstClass = false;
3523 break;
3524 }
3525
qining25262b32016-05-06 17:25:16 -04003526 if (firstClass) {
3527 spv::Id result = builder.createBinOp(op, typeId, left, right);
3528 addDecoration(result, noContraction);
3529 return builder.setPrecision(result, precision);
3530 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003531
LoopDawg592860c2016-06-09 08:57:35 -06003532 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003533 // The result type of all of them is the same type as the (a) matrix operand.
3534 // The algorithm is to:
3535 // - break the matrix(es) into vectors
3536 // - smear any scalar to a vector
3537 // - do vector operations
3538 // - make a matrix out the vector results
3539 switch (op) {
3540 case spv::OpFAdd:
3541 case spv::OpFSub:
3542 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003543 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003544 case spv::OpFMul:
3545 {
3546 // one time set up...
3547 bool leftMat = builder.isMatrix(left);
3548 bool rightMat = builder.isMatrix(right);
3549 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3550 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3551 spv::Id scalarType = builder.getScalarTypeId(typeId);
3552 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3553 std::vector<spv::Id> results;
3554 spv::Id smearVec = spv::NoResult;
3555 if (builder.isScalar(left))
3556 smearVec = builder.smearScalar(precision, left, vecType);
3557 else if (builder.isScalar(right))
3558 smearVec = builder.smearScalar(precision, right, vecType);
3559
3560 // do each vector op
3561 for (unsigned int c = 0; c < numCols; ++c) {
3562 std::vector<unsigned int> indexes;
3563 indexes.push_back(c);
3564 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3565 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003566 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3567 addDecoration(result, noContraction);
3568 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003569 }
3570
3571 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003572 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003573 }
3574 default:
3575 assert(0);
3576 return spv::NoResult;
3577 }
3578}
3579
qining25262b32016-05-06 17:25:16 -04003580spv::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 -06003581{
3582 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003583 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003584 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003585 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003586#ifdef AMD_EXTENSIONS
3587 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3588#else
Rex Xu04db3f52015-09-16 11:44:02 +08003589 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003590#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003591
3592 switch (op) {
3593 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003594 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003595 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003596 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003597 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003598 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003599 unaryOp = spv::OpSNegate;
3600 break;
3601
3602 case glslang::EOpLogicalNot:
3603 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 unaryOp = spv::OpLogicalNot;
3605 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003606 case glslang::EOpBitwiseNot:
3607 unaryOp = spv::OpNot;
3608 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003609
John Kessenich140f3df2015-06-26 16:58:36 -06003610 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003611 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003612 break;
3613 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003614 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003615 break;
3616 case glslang::EOpTranspose:
3617 unaryOp = spv::OpTranspose;
3618 break;
3619
3620 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003621 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003622 break;
3623 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003624 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003625 break;
3626 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003627 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003628 break;
3629 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003630 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003631 break;
3632 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003633 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003634 break;
3635 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003636 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003637 break;
3638 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
3644
3645 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003646 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003647 break;
3648 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003649 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003652 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003653 break;
3654 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003655 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 break;
3657 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003658 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003659 break;
3660 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003661 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003662 break;
3663
3664 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003665 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003666 break;
3667 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003668 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003669 break;
3670
3671 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003672 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003673 break;
3674 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003675 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003676 break;
3677 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003678 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003679 break;
3680 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003681 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003682 break;
3683 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003684 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003685 break;
3686 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003687 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
3689
3690 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003691 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003692 break;
3693 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003694 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 break;
3696 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003698 break;
3699 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003700 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003703 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 break;
3705 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003706 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003707 break;
3708
3709 case glslang::EOpIsNan:
3710 unaryOp = spv::OpIsNan;
3711 break;
3712 case glslang::EOpIsInf:
3713 unaryOp = spv::OpIsInf;
3714 break;
LoopDawg592860c2016-06-09 08:57:35 -06003715 case glslang::EOpIsFinite:
3716 unaryOp = spv::OpIsFinite;
3717 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003718
Rex Xucbc426e2015-12-15 16:03:10 +08003719 case glslang::EOpFloatBitsToInt:
3720 case glslang::EOpFloatBitsToUint:
3721 case glslang::EOpIntBitsToFloat:
3722 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003723 case glslang::EOpDoubleBitsToInt64:
3724 case glslang::EOpDoubleBitsToUint64:
3725 case glslang::EOpInt64BitsToDouble:
3726 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003727 unaryOp = spv::OpBitcast;
3728 break;
3729
John Kessenich140f3df2015-06-26 16:58:36 -06003730 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003731 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003734 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003741 break;
3742 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003746 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003748 case glslang::EOpPackSnorm4x8:
3749 libCall = spv::GLSLstd450PackSnorm4x8;
3750 break;
3751 case glslang::EOpUnpackSnorm4x8:
3752 libCall = spv::GLSLstd450UnpackSnorm4x8;
3753 break;
3754 case glslang::EOpPackUnorm4x8:
3755 libCall = spv::GLSLstd450PackUnorm4x8;
3756 break;
3757 case glslang::EOpUnpackUnorm4x8:
3758 libCall = spv::GLSLstd450UnpackUnorm4x8;
3759 break;
3760 case glslang::EOpPackDouble2x32:
3761 libCall = spv::GLSLstd450PackDouble2x32;
3762 break;
3763 case glslang::EOpUnpackDouble2x32:
3764 libCall = spv::GLSLstd450UnpackDouble2x32;
3765 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003766
Rex Xu8ff43de2016-04-22 16:51:45 +08003767 case glslang::EOpPackInt2x32:
3768 case glslang::EOpUnpackInt2x32:
3769 case glslang::EOpPackUint2x32:
3770 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003771 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003772 break;
3773
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003774#ifdef AMD_EXTENSIONS
3775 case glslang::EOpPackFloat2x16:
3776 case glslang::EOpUnpackFloat2x16:
3777 unaryOp = spv::OpBitcast;
3778 break;
3779#endif
3780
John Kessenich140f3df2015-06-26 16:58:36 -06003781 case glslang::EOpDPdx:
3782 unaryOp = spv::OpDPdx;
3783 break;
3784 case glslang::EOpDPdy:
3785 unaryOp = spv::OpDPdy;
3786 break;
3787 case glslang::EOpFwidth:
3788 unaryOp = spv::OpFwidth;
3789 break;
3790 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003791 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003792 unaryOp = spv::OpDPdxFine;
3793 break;
3794 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003795 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003796 unaryOp = spv::OpDPdyFine;
3797 break;
3798 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003799 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 unaryOp = spv::OpFwidthFine;
3801 break;
3802 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003803 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003804 unaryOp = spv::OpDPdxCoarse;
3805 break;
3806 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003807 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003808 unaryOp = spv::OpDPdyCoarse;
3809 break;
3810 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003811 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003812 unaryOp = spv::OpFwidthCoarse;
3813 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003814 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003815 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003816 libCall = spv::GLSLstd450InterpolateAtCentroid;
3817 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003818 case glslang::EOpAny:
3819 unaryOp = spv::OpAny;
3820 break;
3821 case glslang::EOpAll:
3822 unaryOp = spv::OpAll;
3823 break;
3824
3825 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 if (isFloat)
3827 libCall = spv::GLSLstd450FAbs;
3828 else
3829 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003832 if (isFloat)
3833 libCall = spv::GLSLstd450FSign;
3834 else
3835 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837
John Kessenichfc51d282015-08-19 13:34:18 -06003838 case glslang::EOpAtomicCounterIncrement:
3839 case glslang::EOpAtomicCounterDecrement:
3840 case glslang::EOpAtomicCounter:
3841 {
3842 // Handle all of the atomics in one place, in createAtomicOperation()
3843 std::vector<spv::Id> operands;
3844 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003845 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003846 }
3847
John Kessenichfc51d282015-08-19 13:34:18 -06003848 case glslang::EOpBitFieldReverse:
3849 unaryOp = spv::OpBitReverse;
3850 break;
3851 case glslang::EOpBitCount:
3852 unaryOp = spv::OpBitCount;
3853 break;
3854 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003855 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003856 break;
3857 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003858 if (isUnsigned)
3859 libCall = spv::GLSLstd450FindUMsb;
3860 else
3861 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003862 break;
3863
Rex Xu574ab042016-04-14 16:53:07 +08003864 case glslang::EOpBallot:
3865 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003866 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003867 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003868 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003869#ifdef AMD_EXTENSIONS
3870 case glslang::EOpMinInvocations:
3871 case glslang::EOpMaxInvocations:
3872 case glslang::EOpAddInvocations:
3873 case glslang::EOpMinInvocationsNonUniform:
3874 case glslang::EOpMaxInvocationsNonUniform:
3875 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003876 case glslang::EOpMinInvocationsInclusiveScan:
3877 case glslang::EOpMaxInvocationsInclusiveScan:
3878 case glslang::EOpAddInvocationsInclusiveScan:
3879 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3880 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3881 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3882 case glslang::EOpMinInvocationsExclusiveScan:
3883 case glslang::EOpMaxInvocationsExclusiveScan:
3884 case glslang::EOpAddInvocationsExclusiveScan:
3885 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3886 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3887 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003888#endif
Rex Xu51596642016-09-21 18:56:12 +08003889 {
3890 std::vector<spv::Id> operands;
3891 operands.push_back(operand);
3892 return createInvocationsOperation(op, typeId, operands, typeProxy);
3893 }
Rex Xu9d93a232016-05-05 12:30:44 +08003894
3895#ifdef AMD_EXTENSIONS
3896 case glslang::EOpMbcnt:
3897 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3898 libCall = spv::MbcntAMD;
3899 break;
3900
3901 case glslang::EOpCubeFaceIndex:
3902 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3903 libCall = spv::CubeFaceIndexAMD;
3904 break;
3905
3906 case glslang::EOpCubeFaceCoord:
3907 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3908 libCall = spv::CubeFaceCoordAMD;
3909 break;
3910#endif
Rex Xu338b1852016-05-05 20:38:33 +08003911
John Kessenich140f3df2015-06-26 16:58:36 -06003912 default:
3913 return 0;
3914 }
3915
3916 spv::Id id;
3917 if (libCall >= 0) {
3918 std::vector<spv::Id> args;
3919 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003920 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003921 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003922 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003923 }
John Kessenich140f3df2015-06-26 16:58:36 -06003924
qining25262b32016-05-06 17:25:16 -04003925 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003926 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003927}
3928
John Kessenich7a53f762016-01-20 11:19:27 -07003929// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003930spv::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 -07003931{
3932 // Handle unary operations vector by vector.
3933 // The result type is the same type as the original type.
3934 // The algorithm is to:
3935 // - break the matrix into vectors
3936 // - apply the operation to each vector
3937 // - make a matrix out the vector results
3938
3939 // get the types sorted out
3940 int numCols = builder.getNumColumns(operand);
3941 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003942 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3943 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003944 std::vector<spv::Id> results;
3945
3946 // do each vector op
3947 for (int c = 0; c < numCols; ++c) {
3948 std::vector<unsigned int> indexes;
3949 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003950 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3951 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3952 addDecoration(destVec, noContraction);
3953 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003954 }
3955
3956 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003957 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003958}
3959
Rex Xu73e3ce72016-04-27 18:48:17 +08003960spv::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 -06003961{
3962 spv::Op convOp = spv::OpNop;
3963 spv::Id zero = 0;
3964 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003965 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003966
3967 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3968
3969 switch (op) {
3970 case glslang::EOpConvIntToBool:
3971 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003972 case glslang::EOpConvInt64ToBool:
3973 case glslang::EOpConvUint64ToBool:
3974 zero = (op == glslang::EOpConvInt64ToBool ||
3975 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003976 zero = makeSmearedConstant(zero, vectorSize);
3977 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3978
3979 case glslang::EOpConvFloatToBool:
3980 zero = builder.makeFloatConstant(0.0F);
3981 zero = makeSmearedConstant(zero, vectorSize);
3982 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3983
3984 case glslang::EOpConvDoubleToBool:
3985 zero = builder.makeDoubleConstant(0.0);
3986 zero = makeSmearedConstant(zero, vectorSize);
3987 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3988
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003989#ifdef AMD_EXTENSIONS
3990 case glslang::EOpConvFloat16ToBool:
3991 zero = builder.makeFloat16Constant(0.0F);
3992 zero = makeSmearedConstant(zero, vectorSize);
3993 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3994#endif
3995
John Kessenich140f3df2015-06-26 16:58:36 -06003996 case glslang::EOpConvBoolToFloat:
3997 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003998 zero = builder.makeFloatConstant(0.0F);
3999 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004000 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004001
John Kessenich140f3df2015-06-26 16:58:36 -06004002 case glslang::EOpConvBoolToDouble:
4003 convOp = spv::OpSelect;
4004 zero = builder.makeDoubleConstant(0.0);
4005 one = builder.makeDoubleConstant(1.0);
4006 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004007
4008#ifdef AMD_EXTENSIONS
4009 case glslang::EOpConvBoolToFloat16:
4010 convOp = spv::OpSelect;
4011 zero = builder.makeFloat16Constant(0.0F);
4012 one = builder.makeFloat16Constant(1.0F);
4013 break;
4014#endif
4015
John Kessenich140f3df2015-06-26 16:58:36 -06004016 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004017 case glslang::EOpConvBoolToInt64:
4018 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4019 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004020 convOp = spv::OpSelect;
4021 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004022
John Kessenich140f3df2015-06-26 16:58:36 -06004023 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004024 case glslang::EOpConvBoolToUint64:
4025 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4026 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004027 convOp = spv::OpSelect;
4028 break;
4029
4030 case glslang::EOpConvIntToFloat:
4031 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004032 case glslang::EOpConvInt64ToFloat:
4033 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004034#ifdef AMD_EXTENSIONS
4035 case glslang::EOpConvIntToFloat16:
4036 case glslang::EOpConvInt64ToFloat16:
4037#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004038 convOp = spv::OpConvertSToF;
4039 break;
4040
4041 case glslang::EOpConvUintToFloat:
4042 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004043 case glslang::EOpConvUint64ToFloat:
4044 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004045#ifdef AMD_EXTENSIONS
4046 case glslang::EOpConvUintToFloat16:
4047 case glslang::EOpConvUint64ToFloat16:
4048#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004049 convOp = spv::OpConvertUToF;
4050 break;
4051
4052 case glslang::EOpConvDoubleToFloat:
4053 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004054#ifdef AMD_EXTENSIONS
4055 case glslang::EOpConvDoubleToFloat16:
4056 case glslang::EOpConvFloat16ToDouble:
4057 case glslang::EOpConvFloatToFloat16:
4058 case glslang::EOpConvFloat16ToFloat:
4059#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004060 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004061 if (builder.isMatrixType(destType))
4062 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064
4065 case glslang::EOpConvFloatToInt:
4066 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004067 case glslang::EOpConvFloatToInt64:
4068 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004069#ifdef AMD_EXTENSIONS
4070 case glslang::EOpConvFloat16ToInt:
4071 case glslang::EOpConvFloat16ToInt64:
4072#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004073 convOp = spv::OpConvertFToS;
4074 break;
4075
4076 case glslang::EOpConvUintToInt:
4077 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004078 case glslang::EOpConvUint64ToInt64:
4079 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004080 if (builder.isInSpecConstCodeGenMode()) {
4081 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004082 zero = (op == glslang::EOpConvUint64ToInt64 ||
4083 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004084 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004085 // Use OpIAdd, instead of OpBitcast to do the conversion when
4086 // generating for OpSpecConstantOp instruction.
4087 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4088 }
4089 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004090 convOp = spv::OpBitcast;
4091 break;
4092
4093 case glslang::EOpConvFloatToUint:
4094 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004095 case glslang::EOpConvFloatToUint64:
4096 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004097#ifdef AMD_EXTENSIONS
4098 case glslang::EOpConvFloat16ToUint:
4099 case glslang::EOpConvFloat16ToUint64:
4100#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004101 convOp = spv::OpConvertFToU;
4102 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004103
4104 case glslang::EOpConvIntToInt64:
4105 case glslang::EOpConvInt64ToInt:
4106 convOp = spv::OpSConvert;
4107 break;
4108
4109 case glslang::EOpConvUintToUint64:
4110 case glslang::EOpConvUint64ToUint:
4111 convOp = spv::OpUConvert;
4112 break;
4113
4114 case glslang::EOpConvIntToUint64:
4115 case glslang::EOpConvInt64ToUint:
4116 case glslang::EOpConvUint64ToInt:
4117 case glslang::EOpConvUintToInt64:
4118 // OpSConvert/OpUConvert + OpBitCast
4119 switch (op) {
4120 case glslang::EOpConvIntToUint64:
4121 convOp = spv::OpSConvert;
4122 type = builder.makeIntType(64);
4123 break;
4124 case glslang::EOpConvInt64ToUint:
4125 convOp = spv::OpSConvert;
4126 type = builder.makeIntType(32);
4127 break;
4128 case glslang::EOpConvUint64ToInt:
4129 convOp = spv::OpUConvert;
4130 type = builder.makeUintType(32);
4131 break;
4132 case glslang::EOpConvUintToInt64:
4133 convOp = spv::OpUConvert;
4134 type = builder.makeUintType(64);
4135 break;
4136 default:
4137 assert(0);
4138 break;
4139 }
4140
4141 if (vectorSize > 0)
4142 type = builder.makeVectorType(type, vectorSize);
4143
4144 operand = builder.createUnaryOp(convOp, type, operand);
4145
4146 if (builder.isInSpecConstCodeGenMode()) {
4147 // Build zero scalar or vector for OpIAdd.
4148 zero = (op == glslang::EOpConvIntToUint64 ||
4149 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4150 zero = makeSmearedConstant(zero, vectorSize);
4151 // Use OpIAdd, instead of OpBitcast to do the conversion when
4152 // generating for OpSpecConstantOp instruction.
4153 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4154 }
4155 // For normal run-time conversion instruction, use OpBitcast.
4156 convOp = spv::OpBitcast;
4157 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004158 default:
4159 break;
4160 }
4161
4162 spv::Id result = 0;
4163 if (convOp == spv::OpNop)
4164 return result;
4165
4166 if (convOp == spv::OpSelect) {
4167 zero = makeSmearedConstant(zero, vectorSize);
4168 one = makeSmearedConstant(one, vectorSize);
4169 result = builder.createTriOp(convOp, destType, operand, one, zero);
4170 } else
4171 result = builder.createUnaryOp(convOp, destType, operand);
4172
John Kessenich32cfd492016-02-02 12:37:46 -07004173 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004174}
4175
4176spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4177{
4178 if (vectorSize == 0)
4179 return constant;
4180
4181 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4182 std::vector<spv::Id> components;
4183 for (int c = 0; c < vectorSize; ++c)
4184 components.push_back(constant);
4185 return builder.makeCompositeConstant(vectorTypeId, components);
4186}
4187
John Kessenich426394d2015-07-23 10:22:48 -06004188// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004189spv::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 -06004190{
4191 spv::Op opCode = spv::OpNop;
4192
4193 switch (op) {
4194 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004195 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004196 opCode = spv::OpAtomicIAdd;
4197 break;
4198 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004199 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004200 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004201 break;
4202 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004203 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004204 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004205 break;
4206 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004207 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004208 opCode = spv::OpAtomicAnd;
4209 break;
4210 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004211 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004212 opCode = spv::OpAtomicOr;
4213 break;
4214 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004215 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004216 opCode = spv::OpAtomicXor;
4217 break;
4218 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004219 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004220 opCode = spv::OpAtomicExchange;
4221 break;
4222 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004223 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004224 opCode = spv::OpAtomicCompareExchange;
4225 break;
4226 case glslang::EOpAtomicCounterIncrement:
4227 opCode = spv::OpAtomicIIncrement;
4228 break;
4229 case glslang::EOpAtomicCounterDecrement:
4230 opCode = spv::OpAtomicIDecrement;
4231 break;
4232 case glslang::EOpAtomicCounter:
4233 opCode = spv::OpAtomicLoad;
4234 break;
4235 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004236 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004237 break;
4238 }
4239
4240 // Sort out the operands
4241 // - mapping from glslang -> SPV
4242 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004243 // - compare-exchange swaps the value and comparator
4244 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004245 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4246 auto opIt = operands.begin(); // walk the glslang operands
4247 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004248 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4249 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4250 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004251 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4252 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004253 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004254 spvAtomicOperands.push_back(*(opIt + 1));
4255 spvAtomicOperands.push_back(*opIt);
4256 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004257 }
John Kessenich426394d2015-07-23 10:22:48 -06004258
John Kessenich3e60a6f2015-09-14 22:45:16 -06004259 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004260 for (; opIt != operands.end(); ++opIt)
4261 spvAtomicOperands.push_back(*opIt);
4262
4263 return builder.createOp(opCode, typeId, spvAtomicOperands);
4264}
4265
John Kessenich91cef522016-05-05 16:45:40 -06004266// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004267spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004268{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004269#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004270 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004271 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004272#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004273
Rex Xu51596642016-09-21 18:56:12 +08004274 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004275 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004276 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4277
chaocf200da82016-12-20 12:44:35 -08004278 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4279 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004280 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4281 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004282 } else if (op == glslang::EOpAnyInvocation ||
4283 op == glslang::EOpAllInvocations ||
4284 op == glslang::EOpAllInvocationsEqual) {
4285 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4286 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004287 } else {
4288 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004289#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004290 if (op == glslang::EOpMinInvocationsNonUniform ||
4291 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004292 op == glslang::EOpAddInvocationsNonUniform ||
4293 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4294 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4295 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4296 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4297 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4298 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004299 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004300#endif
Rex Xu51596642016-09-21 18:56:12 +08004301
4302 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004303#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004304 switch (op) {
4305 case glslang::EOpMinInvocations:
4306 case glslang::EOpMaxInvocations:
4307 case glslang::EOpAddInvocations:
4308 case glslang::EOpMinInvocationsNonUniform:
4309 case glslang::EOpMaxInvocationsNonUniform:
4310 case glslang::EOpAddInvocationsNonUniform:
4311 groupOperation = spv::GroupOperationReduce;
4312 spvGroupOperands.push_back(groupOperation);
4313 break;
4314 case glslang::EOpMinInvocationsInclusiveScan:
4315 case glslang::EOpMaxInvocationsInclusiveScan:
4316 case glslang::EOpAddInvocationsInclusiveScan:
4317 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4318 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4319 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4320 groupOperation = spv::GroupOperationInclusiveScan;
4321 spvGroupOperands.push_back(groupOperation);
4322 break;
4323 case glslang::EOpMinInvocationsExclusiveScan:
4324 case glslang::EOpMaxInvocationsExclusiveScan:
4325 case glslang::EOpAddInvocationsExclusiveScan:
4326 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4327 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4328 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4329 groupOperation = spv::GroupOperationExclusiveScan;
4330 spvGroupOperands.push_back(groupOperation);
4331 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004332 default:
4333 break;
Rex Xu430ef402016-10-14 17:22:23 +08004334 }
Rex Xu9d93a232016-05-05 12:30:44 +08004335#endif
Rex Xu51596642016-09-21 18:56:12 +08004336 }
4337
4338 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4339 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004340
4341 switch (op) {
4342 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004343 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004344 break;
John Kessenich91cef522016-05-05 16:45:40 -06004345 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004346 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004347 break;
John Kessenich91cef522016-05-05 16:45:40 -06004348 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004349 opCode = spv::OpSubgroupAllEqualKHR;
4350 break;
Rex Xu51596642016-09-21 18:56:12 +08004351 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004352 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004353 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004354 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004355 break;
4356 case glslang::EOpReadFirstInvocation:
4357 opCode = spv::OpSubgroupFirstInvocationKHR;
4358 break;
4359 case glslang::EOpBallot:
4360 {
4361 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4362 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4363 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4364 //
4365 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4366 //
4367 spv::Id uintType = builder.makeUintType(32);
4368 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4369 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4370
4371 std::vector<spv::Id> components;
4372 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4373 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4374
4375 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4376 return builder.createUnaryOp(spv::OpBitcast, typeId,
4377 builder.createCompositeConstruct(uvec2Type, components));
4378 }
4379
Rex Xu9d93a232016-05-05 12:30:44 +08004380#ifdef AMD_EXTENSIONS
4381 case glslang::EOpMinInvocations:
4382 case glslang::EOpMaxInvocations:
4383 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004384 case glslang::EOpMinInvocationsInclusiveScan:
4385 case glslang::EOpMaxInvocationsInclusiveScan:
4386 case glslang::EOpAddInvocationsInclusiveScan:
4387 case glslang::EOpMinInvocationsExclusiveScan:
4388 case glslang::EOpMaxInvocationsExclusiveScan:
4389 case glslang::EOpAddInvocationsExclusiveScan:
4390 if (op == glslang::EOpMinInvocations ||
4391 op == glslang::EOpMinInvocationsInclusiveScan ||
4392 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004393 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004394 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004395 else {
4396 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004397 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004398 else
Rex Xu51596642016-09-21 18:56:12 +08004399 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004400 }
Rex Xu430ef402016-10-14 17:22:23 +08004401 } else if (op == glslang::EOpMaxInvocations ||
4402 op == glslang::EOpMaxInvocationsInclusiveScan ||
4403 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004404 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004405 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004406 else {
4407 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004408 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004409 else
Rex Xu51596642016-09-21 18:56:12 +08004410 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004411 }
4412 } else {
4413 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004414 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004415 else
Rex Xu51596642016-09-21 18:56:12 +08004416 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004417 }
4418
Rex Xu2bbbe062016-08-23 15:41:05 +08004419 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004420 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004421
4422 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004423 case glslang::EOpMinInvocationsNonUniform:
4424 case glslang::EOpMaxInvocationsNonUniform:
4425 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004426 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4427 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4428 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4429 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4430 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4431 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4432 if (op == glslang::EOpMinInvocationsNonUniform ||
4433 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4434 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004435 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004436 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004437 else {
4438 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004439 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004440 else
Rex Xu51596642016-09-21 18:56:12 +08004441 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004442 }
4443 }
Rex Xu430ef402016-10-14 17:22:23 +08004444 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4445 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4446 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004447 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004448 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004449 else {
4450 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004451 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004452 else
Rex Xu51596642016-09-21 18:56:12 +08004453 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004454 }
4455 }
4456 else {
4457 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004458 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004459 else
Rex Xu51596642016-09-21 18:56:12 +08004460 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004461 }
4462
Rex Xu2bbbe062016-08-23 15:41:05 +08004463 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004464 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004465
4466 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004467#endif
John Kessenich91cef522016-05-05 16:45:40 -06004468 default:
4469 logger->missingFunctionality("invocation operation");
4470 return spv::NoResult;
4471 }
Rex Xu51596642016-09-21 18:56:12 +08004472
4473 assert(opCode != spv::OpNop);
4474 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004475}
4476
Rex Xu2bbbe062016-08-23 15:41:05 +08004477// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004478spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004479{
Rex Xub7072052016-09-26 15:53:40 +08004480#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004481 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4482 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004483 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004484 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004485 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4486 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4487 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004488#else
4489 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4490 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004491 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4492 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004493#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004494
4495 // Handle group invocation operations scalar by scalar.
4496 // The result type is the same type as the original type.
4497 // The algorithm is to:
4498 // - break the vector into scalars
4499 // - apply the operation to each scalar
4500 // - make a vector out the scalar results
4501
4502 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004503 int numComponents = builder.getNumComponents(operands[0]);
4504 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004505 std::vector<spv::Id> results;
4506
4507 // do each scalar op
4508 for (int comp = 0; comp < numComponents; ++comp) {
4509 std::vector<unsigned int> indexes;
4510 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004511 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004512 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004513 if (op == spv::OpSubgroupReadInvocationKHR) {
4514 spvGroupOperands.push_back(scalar);
4515 spvGroupOperands.push_back(operands[1]);
4516 } else if (op == spv::OpGroupBroadcast) {
4517 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004518 spvGroupOperands.push_back(scalar);
4519 spvGroupOperands.push_back(operands[1]);
4520 } else {
chaocf200da82016-12-20 12:44:35 -08004521 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004522 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004523 spvGroupOperands.push_back(scalar);
4524 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004525
Rex Xub7072052016-09-26 15:53:40 +08004526 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004527 }
4528
4529 // put the pieces together
4530 return builder.createCompositeConstruct(typeId, results);
4531}
Rex Xu2bbbe062016-08-23 15:41:05 +08004532
John Kessenich5e4b1242015-08-06 22:53:06 -06004533spv::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 -06004534{
Rex Xu8ff43de2016-04-22 16:51:45 +08004535 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004536#ifdef AMD_EXTENSIONS
4537 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4538#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004539 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004540#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004541
John Kessenich140f3df2015-06-26 16:58:36 -06004542 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004543 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004544 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004545 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004546 spv::Id typeId0 = 0;
4547 if (consumedOperands > 0)
4548 typeId0 = builder.getTypeId(operands[0]);
4549 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004550
4551 switch (op) {
4552 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004553 if (isFloat)
4554 libCall = spv::GLSLstd450FMin;
4555 else if (isUnsigned)
4556 libCall = spv::GLSLstd450UMin;
4557 else
4558 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004559 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004560 break;
4561 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004562 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004563 break;
4564 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004565 if (isFloat)
4566 libCall = spv::GLSLstd450FMax;
4567 else if (isUnsigned)
4568 libCall = spv::GLSLstd450UMax;
4569 else
4570 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004571 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004572 break;
4573 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004574 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004575 break;
4576 case glslang::EOpDot:
4577 opCode = spv::OpDot;
4578 break;
4579 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004580 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004581 break;
4582
4583 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004584 if (isFloat)
4585 libCall = spv::GLSLstd450FClamp;
4586 else if (isUnsigned)
4587 libCall = spv::GLSLstd450UClamp;
4588 else
4589 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004590 builder.promoteScalar(precision, operands.front(), operands[1]);
4591 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004592 break;
4593 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004594 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4595 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004596 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004597 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004598 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004599 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004600 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004601 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004602 break;
4603 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004604 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004605 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004606 break;
4607 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004608 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004609 builder.promoteScalar(precision, operands[0], operands[2]);
4610 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004611 break;
4612
4613 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004614 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004615 break;
4616 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004617 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004618 break;
4619 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004620 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004621 break;
4622 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004623 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004624 break;
4625 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004626 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004627 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004628 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004629 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004630 libCall = spv::GLSLstd450InterpolateAtSample;
4631 break;
4632 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004633 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004634 libCall = spv::GLSLstd450InterpolateAtOffset;
4635 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004636 case glslang::EOpAddCarry:
4637 opCode = spv::OpIAddCarry;
4638 typeId = builder.makeStructResultType(typeId0, typeId0);
4639 consumedOperands = 2;
4640 break;
4641 case glslang::EOpSubBorrow:
4642 opCode = spv::OpISubBorrow;
4643 typeId = builder.makeStructResultType(typeId0, typeId0);
4644 consumedOperands = 2;
4645 break;
4646 case glslang::EOpUMulExtended:
4647 opCode = spv::OpUMulExtended;
4648 typeId = builder.makeStructResultType(typeId0, typeId0);
4649 consumedOperands = 2;
4650 break;
4651 case glslang::EOpIMulExtended:
4652 opCode = spv::OpSMulExtended;
4653 typeId = builder.makeStructResultType(typeId0, typeId0);
4654 consumedOperands = 2;
4655 break;
4656 case glslang::EOpBitfieldExtract:
4657 if (isUnsigned)
4658 opCode = spv::OpBitFieldUExtract;
4659 else
4660 opCode = spv::OpBitFieldSExtract;
4661 break;
4662 case glslang::EOpBitfieldInsert:
4663 opCode = spv::OpBitFieldInsert;
4664 break;
4665
4666 case glslang::EOpFma:
4667 libCall = spv::GLSLstd450Fma;
4668 break;
4669 case glslang::EOpFrexp:
4670 libCall = spv::GLSLstd450FrexpStruct;
4671 if (builder.getNumComponents(operands[0]) == 1)
4672 frexpIntType = builder.makeIntegerType(32, true);
4673 else
4674 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4675 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4676 consumedOperands = 1;
4677 break;
4678 case glslang::EOpLdexp:
4679 libCall = spv::GLSLstd450Ldexp;
4680 break;
4681
Rex Xu574ab042016-04-14 16:53:07 +08004682 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004683 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004684
Rex Xu9d93a232016-05-05 12:30:44 +08004685#ifdef AMD_EXTENSIONS
4686 case glslang::EOpSwizzleInvocations:
4687 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4688 libCall = spv::SwizzleInvocationsAMD;
4689 break;
4690 case glslang::EOpSwizzleInvocationsMasked:
4691 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4692 libCall = spv::SwizzleInvocationsMaskedAMD;
4693 break;
4694 case glslang::EOpWriteInvocation:
4695 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4696 libCall = spv::WriteInvocationAMD;
4697 break;
4698
4699 case glslang::EOpMin3:
4700 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4701 if (isFloat)
4702 libCall = spv::FMin3AMD;
4703 else {
4704 if (isUnsigned)
4705 libCall = spv::UMin3AMD;
4706 else
4707 libCall = spv::SMin3AMD;
4708 }
4709 break;
4710 case glslang::EOpMax3:
4711 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4712 if (isFloat)
4713 libCall = spv::FMax3AMD;
4714 else {
4715 if (isUnsigned)
4716 libCall = spv::UMax3AMD;
4717 else
4718 libCall = spv::SMax3AMD;
4719 }
4720 break;
4721 case glslang::EOpMid3:
4722 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4723 if (isFloat)
4724 libCall = spv::FMid3AMD;
4725 else {
4726 if (isUnsigned)
4727 libCall = spv::UMid3AMD;
4728 else
4729 libCall = spv::SMid3AMD;
4730 }
4731 break;
4732
4733 case glslang::EOpInterpolateAtVertex:
4734 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4735 libCall = spv::InterpolateAtVertexAMD;
4736 break;
4737#endif
4738
John Kessenich140f3df2015-06-26 16:58:36 -06004739 default:
4740 return 0;
4741 }
4742
4743 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004744 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004745 // Use an extended instruction from the standard library.
4746 // Construct the call arguments, without modifying the original operands vector.
4747 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4748 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004749 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004750 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004751 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004752 case 0:
4753 // should all be handled by visitAggregate and createNoArgOperation
4754 assert(0);
4755 return 0;
4756 case 1:
4757 // should all be handled by createUnaryOperation
4758 assert(0);
4759 return 0;
4760 case 2:
4761 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4762 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004763 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004764 // anything 3 or over doesn't have l-value operands, so all should be consumed
4765 assert(consumedOperands == operands.size());
4766 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004767 break;
4768 }
4769 }
4770
John Kessenich55e7d112015-11-15 21:33:39 -07004771 // Decode the return types that were structures
4772 switch (op) {
4773 case glslang::EOpAddCarry:
4774 case glslang::EOpSubBorrow:
4775 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4776 id = builder.createCompositeExtract(id, typeId0, 0);
4777 break;
4778 case glslang::EOpUMulExtended:
4779 case glslang::EOpIMulExtended:
4780 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4781 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4782 break;
4783 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004784 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004785 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4786 id = builder.createCompositeExtract(id, typeId0, 0);
4787 break;
4788 default:
4789 break;
4790 }
4791
John Kessenich32cfd492016-02-02 12:37:46 -07004792 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004793}
4794
Rex Xu9d93a232016-05-05 12:30:44 +08004795// Intrinsics with no arguments (or no return value, and no precision).
4796spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004797{
4798 // TODO: get the barrier operands correct
4799
4800 switch (op) {
4801 case glslang::EOpEmitVertex:
4802 builder.createNoResultOp(spv::OpEmitVertex);
4803 return 0;
4804 case glslang::EOpEndPrimitive:
4805 builder.createNoResultOp(spv::OpEndPrimitive);
4806 return 0;
4807 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004808 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004809 return 0;
4810 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004811 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004812 return 0;
4813 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004814 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004815 return 0;
4816 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004817 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004818 return 0;
4819 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004820 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004821 return 0;
4822 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004823 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004824 return 0;
4825 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004826 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004827 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004828 case glslang::EOpAllMemoryBarrierWithGroupSync:
4829 // Control barrier with non-"None" semantic is also a memory barrier.
4830 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4831 return 0;
4832 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4833 // Control barrier with non-"None" semantic is also a memory barrier.
4834 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4835 return 0;
4836 case glslang::EOpWorkgroupMemoryBarrier:
4837 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4838 return 0;
4839 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4840 // Control barrier with non-"None" semantic is also a memory barrier.
4841 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4842 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004843#ifdef AMD_EXTENSIONS
4844 case glslang::EOpTime:
4845 {
4846 std::vector<spv::Id> args; // Dummy arguments
4847 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4848 return builder.setPrecision(id, precision);
4849 }
4850#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004851 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004852 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004853 return 0;
4854 }
4855}
4856
4857spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4858{
John Kessenich2f273362015-07-18 22:34:27 -06004859 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004860 spv::Id id;
4861 if (symbolValues.end() != iter) {
4862 id = iter->second;
4863 return id;
4864 }
4865
4866 // it was not found, create it
4867 id = createSpvVariable(symbol);
4868 symbolValues[symbol->getId()] = id;
4869
Rex Xuc884b4a2016-06-29 15:03:44 +08004870 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004871 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004872 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004873 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004874 if (symbol->getType().getQualifier().hasSpecConstantId())
4875 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004876 if (symbol->getQualifier().hasIndex())
4877 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4878 if (symbol->getQualifier().hasComponent())
4879 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4880 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004881 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004882 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004883 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004884 if (symbol->getQualifier().hasXfbBuffer())
4885 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4886 if (symbol->getQualifier().hasXfbOffset())
4887 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4888 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004889 // atomic counters use this:
4890 if (symbol->getQualifier().hasOffset())
4891 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004892 }
4893
scygan2c864272016-05-18 18:09:17 +02004894 if (symbol->getQualifier().hasLocation())
4895 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004896 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004897 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004898 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004899 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004900 }
John Kessenich140f3df2015-06-26 16:58:36 -06004901 if (symbol->getQualifier().hasSet())
4902 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004903 else if (IsDescriptorResource(symbol->getType())) {
4904 // default to 0
4905 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4906 }
John Kessenich140f3df2015-06-26 16:58:36 -06004907 if (symbol->getQualifier().hasBinding())
4908 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004909 if (symbol->getQualifier().hasAttachment())
4910 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004911 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004912 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004913 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004914 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004915 if (symbol->getQualifier().hasXfbBuffer())
4916 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4917 }
4918
Rex Xu1da878f2016-02-21 20:59:01 +08004919 if (symbol->getType().isImage()) {
4920 std::vector<spv::Decoration> memory;
4921 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4922 for (unsigned int i = 0; i < memory.size(); ++i)
4923 addDecoration(id, memory[i]);
4924 }
4925
John Kessenich140f3df2015-06-26 16:58:36 -06004926 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004927 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004928 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004929 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004930
John Kessenichecba76f2017-01-06 00:34:48 -07004931#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004932 if (builtIn == spv::BuiltInSampleMask) {
4933 spv::Decoration decoration;
4934 // GL_NV_sample_mask_override_coverage extension
4935 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004936 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004937 else
4938 decoration = (spv::Decoration)spv::DecorationMax;
4939 addDecoration(id, decoration);
4940 if (decoration != spv::DecorationMax) {
4941 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4942 }
4943 }
chaoc771d89f2017-01-13 01:10:53 -08004944 else if (builtIn == spv::BuiltInLayer) {
4945 // SPV_NV_viewport_array2 extension
4946 if (symbol->getQualifier().layoutViewportRelative)
4947 {
4948 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4949 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4950 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4951 }
4952 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4953 {
4954 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4955 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4956 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4957 }
4958 }
4959
chaoc6e5acae2016-12-20 13:28:52 -08004960 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004961 addDecoration(id, spv::DecorationPassthroughNV);
4962 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004963 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4964 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004965#endif
4966
John Kessenich140f3df2015-06-26 16:58:36 -06004967 return id;
4968}
4969
John Kessenich55e7d112015-11-15 21:33:39 -07004970// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004971void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4972{
John Kessenich4016e382016-07-15 11:53:56 -06004973 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004974 builder.addDecoration(id, dec);
4975}
4976
John Kessenich55e7d112015-11-15 21:33:39 -07004977// If 'dec' is valid, add a one-operand decoration to an object
4978void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4979{
John Kessenich4016e382016-07-15 11:53:56 -06004980 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004981 builder.addDecoration(id, dec, value);
4982}
4983
4984// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004985void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4986{
John Kessenich4016e382016-07-15 11:53:56 -06004987 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004988 builder.addMemberDecoration(id, (unsigned)member, dec);
4989}
4990
John Kessenich92187592016-02-01 13:45:25 -07004991// If 'dec' is valid, add a one-operand decoration to a struct member
4992void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4993{
John Kessenich4016e382016-07-15 11:53:56 -06004994 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004995 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4996}
4997
John Kessenich55e7d112015-11-15 21:33:39 -07004998// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004999// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005000//
5001// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5002//
5003// Recursively walk the nodes. The nodes form a tree whose leaves are
5004// regular constants, which themselves are trees that createSpvConstant()
5005// recursively walks. So, this function walks the "top" of the tree:
5006// - emit specialization constant-building instructions for specConstant
5007// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005008spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005009{
John Kessenich7cc0e282016-03-20 00:46:02 -06005010 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005011
qining4f4bb812016-04-03 23:55:17 -04005012 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005013 if (! node.getQualifier().specConstant) {
5014 // hand off to the non-spec-constant path
5015 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5016 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005017 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005018 nextConst, false);
5019 }
5020
5021 // We now know we have a specialization constant to build
5022
John Kessenichd94c0032016-05-30 19:29:40 -06005023 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005024 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5025 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5026 std::vector<spv::Id> dimConstId;
5027 for (int dim = 0; dim < 3; ++dim) {
5028 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5029 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5030 if (specConst)
5031 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5032 }
5033 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5034 }
5035
5036 // An AST node labelled as specialization constant should be a symbol node.
5037 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5038 if (auto* sn = node.getAsSymbolNode()) {
5039 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005040 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5041 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5042 // will set the builder into spec constant op instruction generating mode.
5043 sub_tree->traverse(this);
5044 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005045 } else if (auto* const_union_array = &sn->getConstArray()){
5046 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005047 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5048 builder.addName(id, sn->getName().c_str());
5049 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005050 }
5051 }
qining4f4bb812016-04-03 23:55:17 -04005052
5053 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5054 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005055 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005056 exit(1);
5057 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005058}
5059
John Kessenich140f3df2015-06-26 16:58:36 -06005060// Use 'consts' as the flattened glslang source of scalar constants to recursively
5061// build the aggregate SPIR-V constant.
5062//
5063// If there are not enough elements present in 'consts', 0 will be substituted;
5064// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5065//
qining08408382016-03-21 09:51:37 -04005066spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005067{
5068 // vector of constants for SPIR-V
5069 std::vector<spv::Id> spvConsts;
5070
5071 // Type is used for struct and array constants
5072 spv::Id typeId = convertGlslangToSpvType(glslangType);
5073
5074 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005075 glslang::TType elementType(glslangType, 0);
5076 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005077 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005078 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005079 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005080 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005081 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005082 } else if (glslangType.getStruct()) {
5083 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5084 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005085 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005086 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005087 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5088 bool zero = nextConst >= consts.size();
5089 switch (glslangType.getBasicType()) {
5090 case glslang::EbtInt:
5091 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5092 break;
5093 case glslang::EbtUint:
5094 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5095 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005096 case glslang::EbtInt64:
5097 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5098 break;
5099 case glslang::EbtUint64:
5100 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5101 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005102 case glslang::EbtFloat:
5103 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5104 break;
5105 case glslang::EbtDouble:
5106 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5107 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005108#ifdef AMD_EXTENSIONS
5109 case glslang::EbtFloat16:
5110 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5111 break;
5112#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005113 case glslang::EbtBool:
5114 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5115 break;
5116 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005117 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005118 break;
5119 }
5120 ++nextConst;
5121 }
5122 } else {
5123 // we have a non-aggregate (scalar) constant
5124 bool zero = nextConst >= consts.size();
5125 spv::Id scalar = 0;
5126 switch (glslangType.getBasicType()) {
5127 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005128 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005129 break;
5130 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005131 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005132 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005133 case glslang::EbtInt64:
5134 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5135 break;
5136 case glslang::EbtUint64:
5137 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5138 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005139 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005140 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005141 break;
5142 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005143 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005144 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005145#ifdef AMD_EXTENSIONS
5146 case glslang::EbtFloat16:
5147 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5148 break;
5149#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005150 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005151 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005152 break;
5153 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005154 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005155 break;
5156 }
5157 ++nextConst;
5158 return scalar;
5159 }
5160
5161 return builder.makeCompositeConstant(typeId, spvConsts);
5162}
5163
John Kessenich7c1aa102015-10-15 13:29:11 -06005164// Return true if the node is a constant or symbol whose reading has no
5165// non-trivial observable cost or effect.
5166bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5167{
5168 // don't know what this is
5169 if (node == nullptr)
5170 return false;
5171
5172 // a constant is safe
5173 if (node->getAsConstantUnion() != nullptr)
5174 return true;
5175
5176 // not a symbol means non-trivial
5177 if (node->getAsSymbolNode() == nullptr)
5178 return false;
5179
5180 // a symbol, depends on what's being read
5181 switch (node->getType().getQualifier().storage) {
5182 case glslang::EvqTemporary:
5183 case glslang::EvqGlobal:
5184 case glslang::EvqIn:
5185 case glslang::EvqInOut:
5186 case glslang::EvqConst:
5187 case glslang::EvqConstReadOnly:
5188 case glslang::EvqUniform:
5189 return true;
5190 default:
5191 return false;
5192 }
qining25262b32016-05-06 17:25:16 -04005193}
John Kessenich7c1aa102015-10-15 13:29:11 -06005194
5195// A node is trivial if it is a single operation with no side effects.
5196// Error on the side of saying non-trivial.
5197// Return true if trivial.
5198bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5199{
5200 if (node == nullptr)
5201 return false;
5202
5203 // symbols and constants are trivial
5204 if (isTrivialLeaf(node))
5205 return true;
5206
5207 // otherwise, it needs to be a simple operation or one or two leaf nodes
5208
5209 // not a simple operation
5210 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5211 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5212 if (binaryNode == nullptr && unaryNode == nullptr)
5213 return false;
5214
5215 // not on leaf nodes
5216 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5217 return false;
5218
5219 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5220 return false;
5221 }
5222
5223 switch (node->getAsOperator()->getOp()) {
5224 case glslang::EOpLogicalNot:
5225 case glslang::EOpConvIntToBool:
5226 case glslang::EOpConvUintToBool:
5227 case glslang::EOpConvFloatToBool:
5228 case glslang::EOpConvDoubleToBool:
5229 case glslang::EOpEqual:
5230 case glslang::EOpNotEqual:
5231 case glslang::EOpLessThan:
5232 case glslang::EOpGreaterThan:
5233 case glslang::EOpLessThanEqual:
5234 case glslang::EOpGreaterThanEqual:
5235 case glslang::EOpIndexDirect:
5236 case glslang::EOpIndexDirectStruct:
5237 case glslang::EOpLogicalXor:
5238 case glslang::EOpAny:
5239 case glslang::EOpAll:
5240 return true;
5241 default:
5242 return false;
5243 }
5244}
5245
5246// Emit short-circuiting code, where 'right' is never evaluated unless
5247// the left side is true (for &&) or false (for ||).
5248spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5249{
5250 spv::Id boolTypeId = builder.makeBoolType();
5251
5252 // emit left operand
5253 builder.clearAccessChain();
5254 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005255 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005256
5257 // Operands to accumulate OpPhi operands
5258 std::vector<spv::Id> phiOperands;
5259 // accumulate left operand's phi information
5260 phiOperands.push_back(leftId);
5261 phiOperands.push_back(builder.getBuildPoint()->getId());
5262
5263 // Make the two kinds of operation symmetric with a "!"
5264 // || => emit "if (! left) result = right"
5265 // && => emit "if ( left) result = right"
5266 //
5267 // TODO: this runtime "not" for || could be avoided by adding functionality
5268 // to 'builder' to have an "else" without an "then"
5269 if (op == glslang::EOpLogicalOr)
5270 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5271
5272 // make an "if" based on the left value
5273 spv::Builder::If ifBuilder(leftId, builder);
5274
5275 // emit right operand as the "then" part of the "if"
5276 builder.clearAccessChain();
5277 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005278 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005279
5280 // accumulate left operand's phi information
5281 phiOperands.push_back(rightId);
5282 phiOperands.push_back(builder.getBuildPoint()->getId());
5283
5284 // finish the "if"
5285 ifBuilder.makeEndIf();
5286
5287 // phi together the two results
5288 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5289}
5290
Rex Xu9d93a232016-05-05 12:30:44 +08005291// Return type Id of the imported set of extended instructions corresponds to the name.
5292// Import this set if it has not been imported yet.
5293spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5294{
5295 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5296 return extBuiltinMap[name];
5297 else {
Rex Xu51596642016-09-21 18:56:12 +08005298 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005299 spv::Id extBuiltins = builder.import(name);
5300 extBuiltinMap[name] = extBuiltins;
5301 return extBuiltins;
5302 }
5303}
5304
John Kessenich140f3df2015-06-26 16:58:36 -06005305}; // end anonymous namespace
5306
5307namespace glslang {
5308
John Kessenich68d78fd2015-07-12 19:28:10 -06005309void GetSpirvVersion(std::string& version)
5310{
John Kessenich9e55f632015-07-15 10:03:39 -06005311 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005312 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005313 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005314 version = buf;
5315}
5316
John Kessenich140f3df2015-06-26 16:58:36 -06005317// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005318void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005319{
5320 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005321 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005322 for (int i = 0; i < (int)spirv.size(); ++i) {
5323 unsigned int word = spirv[i];
5324 out.write((const char*)&word, 4);
5325 }
5326 out.close();
5327}
5328
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005329// Write SPIR-V out to a text file with 32-bit hexadecimal words
5330void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5331{
5332 std::ofstream out;
5333 out.open(baseName, std::ios::binary | std::ios::out);
5334 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5335 const int WORDS_PER_LINE = 8;
5336 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5337 out << "\t";
5338 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5339 const unsigned int word = spirv[i + j];
5340 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5341 if (i + j + 1 < (int)spirv.size()) {
5342 out << ",";
5343 }
5344 }
5345 out << std::endl;
5346 }
5347 out.close();
5348}
5349
John Kessenich140f3df2015-06-26 16:58:36 -06005350//
5351// Set up the glslang traversal
5352//
5353void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5354{
Lei Zhang17535f72016-05-04 15:55:59 -04005355 spv::SpvBuildLogger logger;
5356 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005357}
5358
Lei Zhang17535f72016-05-04 15:55:59 -04005359void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005360{
John Kessenich140f3df2015-06-26 16:58:36 -06005361 TIntermNode* root = intermediate.getTreeRoot();
5362
5363 if (root == 0)
5364 return;
5365
5366 glslang::GetThreadPoolAllocator().push();
5367
Lei Zhang17535f72016-05-04 15:55:59 -04005368 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005369 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005370 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005371 it.dumpSpv(spirv);
5372
5373 glslang::GetThreadPoolAllocator().pop();
5374}
5375
5376}; // end namespace glslang