blob: af08e4b00c1d1ffce8d18d615be57398ae43544a [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);
John Kessenich92187592016-02-01 13:45:25 -0700485 return spv::BuiltInViewportIndex;
486
John Kessenich5e801132016-02-15 11:09:46 -0700487 case glslang::EbvSampleId:
488 builder.addCapability(spv::CapabilitySampleRateShading);
489 return spv::BuiltInSampleId;
490
491 case glslang::EbvSamplePosition:
492 builder.addCapability(spv::CapabilitySampleRateShading);
493 return spv::BuiltInSamplePosition;
494
495 case glslang::EbvSampleMask:
496 builder.addCapability(spv::CapabilitySampleRateShading);
497 return spv::BuiltInSampleMask;
498
John Kessenich78a45572016-07-08 14:05:15 -0600499 case glslang::EbvLayer:
500 builder.addCapability(spv::CapabilityGeometry);
501 return spv::BuiltInLayer;
502
John Kessenich140f3df2015-06-26 16:58:36 -0600503 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600504 case glslang::EbvVertexId: return spv::BuiltInVertexId;
505 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700506 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
507 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800508
John Kessenichda581a22015-10-14 14:10:30 -0600509 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800510 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
511 builder.addCapability(spv::CapabilityDrawParameters);
512 return spv::BuiltInBaseVertex;
513
John Kessenichda581a22015-10-14 14:10:30 -0600514 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800515 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
516 builder.addCapability(spv::CapabilityDrawParameters);
517 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200518
John Kessenichda581a22015-10-14 14:10:30 -0600519 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800520 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
521 builder.addCapability(spv::CapabilityDrawParameters);
522 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200523
524 case glslang::EbvPrimitiveId:
525 if (glslangIntermediate->getStage() == EShLangFragment)
526 builder.addCapability(spv::CapabilityGeometry);
527 return spv::BuiltInPrimitiveId;
528
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
531 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
532 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
533 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
534 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
535 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
536 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
538 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
539 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
540 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
541 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
542 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
543 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
544 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800545
Rex Xu574ab042016-04-14 16:53:07 +0800546 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800547 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800548 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
549 return spv::BuiltInSubgroupSize;
550
Rex Xu574ab042016-04-14 16:53:07 +0800551 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800552 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
554 return spv::BuiltInSubgroupLocalInvocationId;
555
Rex Xu574ab042016-04-14 16:53:07 +0800556 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800557 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
558 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
559 return spv::BuiltInSubgroupEqMaskKHR;
560
Rex Xu574ab042016-04-14 16:53:07 +0800561 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800562 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
563 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
564 return spv::BuiltInSubgroupGeMaskKHR;
565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupGtMaskKHR;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLeMaskKHR;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupLtMaskKHR;
580
Rex Xu9d93a232016-05-05 12:30:44 +0800581#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800582 case glslang::EbvBaryCoordNoPersp:
583 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
584 return spv::BuiltInBaryCoordNoPerspAMD;
585
586 case glslang::EbvBaryCoordNoPerspCentroid:
587 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
588 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
589
590 case glslang::EbvBaryCoordNoPerspSample:
591 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
592 return spv::BuiltInBaryCoordNoPerspSampleAMD;
593
594 case glslang::EbvBaryCoordSmooth:
595 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
596 return spv::BuiltInBaryCoordSmoothAMD;
597
598 case glslang::EbvBaryCoordSmoothCentroid:
599 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
600 return spv::BuiltInBaryCoordSmoothCentroidAMD;
601
602 case glslang::EbvBaryCoordSmoothSample:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordSmoothSampleAMD;
605
606 case glslang::EbvBaryCoordPullModel:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800609#endif
John Kessenich4016e382016-07-15 11:53:56 -0600610 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600611 }
612}
613
Rex Xufc618912015-09-09 16:42:49 +0800614// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700615spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800616{
617 assert(type.getBasicType() == glslang::EbtSampler);
618
John Kessenich5d0fa972016-02-15 11:57:00 -0700619 // Check for capabilities
620 switch (type.getQualifier().layoutFormat) {
621 case glslang::ElfRg32f:
622 case glslang::ElfRg16f:
623 case glslang::ElfR11fG11fB10f:
624 case glslang::ElfR16f:
625 case glslang::ElfRgba16:
626 case glslang::ElfRgb10A2:
627 case glslang::ElfRg16:
628 case glslang::ElfRg8:
629 case glslang::ElfR16:
630 case glslang::ElfR8:
631 case glslang::ElfRgba16Snorm:
632 case glslang::ElfRg16Snorm:
633 case glslang::ElfRg8Snorm:
634 case glslang::ElfR16Snorm:
635 case glslang::ElfR8Snorm:
636
637 case glslang::ElfRg32i:
638 case glslang::ElfRg16i:
639 case glslang::ElfRg8i:
640 case glslang::ElfR16i:
641 case glslang::ElfR8i:
642
643 case glslang::ElfRgb10a2ui:
644 case glslang::ElfRg32ui:
645 case glslang::ElfRg16ui:
646 case glslang::ElfRg8ui:
647 case glslang::ElfR16ui:
648 case glslang::ElfR8ui:
649 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
650 break;
651
652 default:
653 break;
654 }
655
656 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800657 switch (type.getQualifier().layoutFormat) {
658 case glslang::ElfNone: return spv::ImageFormatUnknown;
659 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
660 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
661 case glslang::ElfR32f: return spv::ImageFormatR32f;
662 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
663 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
664 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
665 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
666 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
667 case glslang::ElfR16f: return spv::ImageFormatR16f;
668 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
669 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
670 case glslang::ElfRg16: return spv::ImageFormatRg16;
671 case glslang::ElfRg8: return spv::ImageFormatRg8;
672 case glslang::ElfR16: return spv::ImageFormatR16;
673 case glslang::ElfR8: return spv::ImageFormatR8;
674 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
675 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
676 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
677 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
678 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
679 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
680 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
681 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
682 case glslang::ElfR32i: return spv::ImageFormatR32i;
683 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
684 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
685 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
686 case glslang::ElfR16i: return spv::ImageFormatR16i;
687 case glslang::ElfR8i: return spv::ImageFormatR8i;
688 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
689 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
690 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
691 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
692 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
693 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
694 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
695 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
696 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
697 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600698 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800699 }
700}
701
qining25262b32016-05-06 17:25:16 -0400702// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700703// descriptor set.
704bool IsDescriptorResource(const glslang::TType& type)
705{
John Kessenichf7497e22016-03-08 21:36:22 -0700706 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700707 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700708 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700709
710 // non block...
711 // basically samplerXXX/subpass/sampler/texture are all included
712 // if they are the global-scope-class, not the function parameter
713 // (or local, if they ever exist) class.
714 if (type.getBasicType() == glslang::EbtSampler)
715 return type.getQualifier().isUniformOrBuffer();
716
717 // None of the above.
718 return false;
719}
720
John Kesseniche0b6cad2015-12-24 10:30:13 -0700721void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
722{
723 if (child.layoutMatrix == glslang::ElmNone)
724 child.layoutMatrix = parent.layoutMatrix;
725
726 if (parent.invariant)
727 child.invariant = true;
728 if (parent.nopersp)
729 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800730#ifdef AMD_EXTENSIONS
731 if (parent.explicitInterp)
732 child.explicitInterp = true;
733#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700734 if (parent.flat)
735 child.flat = true;
736 if (parent.centroid)
737 child.centroid = true;
738 if (parent.patch)
739 child.patch = true;
740 if (parent.sample)
741 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800742 if (parent.coherent)
743 child.coherent = true;
744 if (parent.volatil)
745 child.volatil = true;
746 if (parent.restrict)
747 child.restrict = true;
748 if (parent.readonly)
749 child.readonly = true;
750 if (parent.writeonly)
751 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700752}
753
John Kessenichf2b7f332016-09-01 17:05:23 -0600754bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700755{
John Kessenich7b9fa252016-01-21 18:56:57 -0700756 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600757 // - struct members might inherit from a struct declaration
758 // (note that non-block structs don't explicitly inherit,
759 // only implicitly, meaning no decoration involved)
760 // - affect decorations on the struct members
761 // (note smooth does not, and expecting something like volatile
762 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700763 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600764 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700765}
766
John Kessenich140f3df2015-06-26 16:58:36 -0600767//
768// Implement the TGlslangToSpvTraverser class.
769//
770
Lei Zhang17535f72016-05-04 15:55:59 -0400771TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600772 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
773 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400774 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700775 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600776 glslangIntermediate(glslangIntermediate)
777{
778 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
779
780 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700781 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600782 stdBuiltins = builder.import("GLSL.std.450");
783 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600784 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
785 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600786
787 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600788 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
789 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600790 builder.addSourceExtension(it->c_str());
791
792 // Add the top-level modes for this shader.
793
John Kessenich92187592016-02-01 13:45:25 -0700794 if (glslangIntermediate->getXfbMode()) {
795 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600796 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700797 }
John Kessenich140f3df2015-06-26 16:58:36 -0600798
799 unsigned int mode;
800 switch (glslangIntermediate->getStage()) {
801 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600802 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600803 break;
804
805 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600806 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600807 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
808 break;
809
810 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600811 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600812 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700813 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
814 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
815 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600816 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600817 }
John Kessenich4016e382016-07-15 11:53:56 -0600818 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600819 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
820
John Kesseniche6903322015-10-13 16:29:02 -0600821 switch (glslangIntermediate->getVertexSpacing()) {
822 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
823 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
824 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600825 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600826 }
John Kessenich4016e382016-07-15 11:53:56 -0600827 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600828 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
829
830 switch (glslangIntermediate->getVertexOrder()) {
831 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
832 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600833 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600834 }
John Kessenich4016e382016-07-15 11:53:56 -0600835 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600836 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
837
838 if (glslangIntermediate->getPointMode())
839 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600840 break;
841
842 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600843 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600844 switch (glslangIntermediate->getInputPrimitive()) {
845 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
846 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
847 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700848 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600849 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600850 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600851 }
John Kessenich4016e382016-07-15 11:53:56 -0600852 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600853 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600854
John Kessenich140f3df2015-06-26 16:58:36 -0600855 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
856
857 switch (glslangIntermediate->getOutputPrimitive()) {
858 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
859 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
860 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600861 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600862 }
John Kessenich4016e382016-07-15 11:53:56 -0600863 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600864 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
865 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
866 break;
867
868 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600869 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600870 if (glslangIntermediate->getPixelCenterInteger())
871 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600872
John Kessenich140f3df2015-06-26 16:58:36 -0600873 if (glslangIntermediate->getOriginUpperLeft())
874 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600875 else
876 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600877
878 if (glslangIntermediate->getEarlyFragmentTests())
879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
880
881 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600882 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
883 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600884 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600885 }
John Kessenich4016e382016-07-15 11:53:56 -0600886 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600887 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
888
889 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
890 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600891 break;
892
893 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600894 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600895 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
896 glslangIntermediate->getLocalSize(1),
897 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600898 break;
899
900 default:
901 break;
902 }
John Kessenich140f3df2015-06-26 16:58:36 -0600903}
904
John Kessenichfca82622016-11-26 13:23:20 -0700905// Finish creating SPV, after the traversal is complete.
906void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700907{
John Kessenich517fe7a2016-11-26 13:31:47 -0700908 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700909 builder.setBuildPoint(shaderEntry->getLastBlock());
910 builder.leaveFunction();
911 }
912
John Kessenich7ba63412015-12-20 17:37:07 -0700913 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100914 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
915 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700916
qiningda397332016-03-09 19:54:03 -0500917 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700918}
919
John Kessenichfca82622016-11-26 13:23:20 -0700920// Write the SPV into 'out'.
921void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600922{
John Kessenichfca82622016-11-26 13:23:20 -0700923 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600924}
925
926//
927// Implement the traversal functions.
928//
929// Return true from interior nodes to have the external traversal
930// continue on to children. Return false if children were
931// already processed.
932//
933
934//
qining25262b32016-05-06 17:25:16 -0400935// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600936// - uniform/input reads
937// - output writes
938// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
939// - something simple that degenerates into the last bullet
940//
941void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
942{
qining75d1d802016-04-06 14:42:01 -0400943 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
944 if (symbol->getType().getQualifier().isSpecConstant())
945 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
946
John Kessenich140f3df2015-06-26 16:58:36 -0600947 // getSymbolId() will set up all the IO decorations on the first call.
948 // Formal function parameters were mapped during makeFunctions().
949 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700950
951 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
952 if (builder.isPointer(id)) {
953 spv::StorageClass sc = builder.getStorageClass(id);
954 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
955 iOSet.insert(id);
956 }
957
958 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700959 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600960 // Prepare to generate code for the access
961
962 // L-value chains will be computed left to right. We're on the symbol now,
963 // which is the left-most part of the access chain, so now is "clear" time,
964 // followed by setting the base.
965 builder.clearAccessChain();
966
967 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700968 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600969 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700970 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600971 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700972 // These are also pure R-values.
973 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600974 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600975 builder.setAccessChainRValue(id);
976 else
977 builder.setAccessChainLValue(id);
978 }
979}
980
981bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
982{
qining40887662016-04-03 22:20:42 -0400983 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
984 if (node->getType().getQualifier().isSpecConstant())
985 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
986
John Kessenich140f3df2015-06-26 16:58:36 -0600987 // First, handle special cases
988 switch (node->getOp()) {
989 case glslang::EOpAssign:
990 case glslang::EOpAddAssign:
991 case glslang::EOpSubAssign:
992 case glslang::EOpMulAssign:
993 case glslang::EOpVectorTimesMatrixAssign:
994 case glslang::EOpVectorTimesScalarAssign:
995 case glslang::EOpMatrixTimesScalarAssign:
996 case glslang::EOpMatrixTimesMatrixAssign:
997 case glslang::EOpDivAssign:
998 case glslang::EOpModAssign:
999 case glslang::EOpAndAssign:
1000 case glslang::EOpInclusiveOrAssign:
1001 case glslang::EOpExclusiveOrAssign:
1002 case glslang::EOpLeftShiftAssign:
1003 case glslang::EOpRightShiftAssign:
1004 // A bin-op assign "a += b" means the same thing as "a = a + b"
1005 // where a is evaluated before b. For a simple assignment, GLSL
1006 // says to evaluate the left before the right. So, always, left
1007 // node then right node.
1008 {
1009 // get the left l-value, save it away
1010 builder.clearAccessChain();
1011 node->getLeft()->traverse(this);
1012 spv::Builder::AccessChain lValue = builder.getAccessChain();
1013
1014 // evaluate the right
1015 builder.clearAccessChain();
1016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001017 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001018
1019 if (node->getOp() != glslang::EOpAssign) {
1020 // the left is also an r-value
1021 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001022 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001023
1024 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001025 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001026 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001027 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1028 node->getType().getBasicType());
1029
1030 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001031 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001032 }
1033
1034 // store the result
1035 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001036 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001037
1038 // assignments are expressions having an rValue after they are evaluated...
1039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(rValue);
1041 }
1042 return false;
1043 case glslang::EOpIndexDirect:
1044 case glslang::EOpIndexDirectStruct:
1045 {
1046 // Get the left part of the access chain.
1047 node->getLeft()->traverse(this);
1048
1049 // Add the next element in the chain
1050
David Netoa901ffe2016-06-08 14:11:40 +01001051 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001052 if (! node->getLeft()->getType().isArray() &&
1053 node->getLeft()->getType().isVector() &&
1054 node->getOp() == glslang::EOpIndexDirect) {
1055 // This is essentially a hard-coded vector swizzle of size 1,
1056 // so short circuit the access-chain stuff with a swizzle.
1057 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001058 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001059 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001060 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001061 int spvIndex = glslangIndex;
1062 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1063 node->getOp() == glslang::EOpIndexDirectStruct)
1064 {
1065 // This may be, e.g., an anonymous block-member selection, which generally need
1066 // index remapping due to hidden members in anonymous blocks.
1067 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1068 assert(remapper.size() > 0);
1069 spvIndex = remapper[glslangIndex];
1070 }
John Kessenichebb50532016-05-16 19:22:05 -06001071
David Netoa901ffe2016-06-08 14:11:40 +01001072 // normal case for indexing array or structure or block
1073 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1074
1075 // Add capabilities here for accessing PointSize and clip/cull distance.
1076 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001077 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001078 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001079 }
1080 }
1081 return false;
1082 case glslang::EOpIndexIndirect:
1083 {
1084 // Structure or array or vector indirection.
1085 // Will use native SPIR-V access-chain for struct and array indirection;
1086 // matrices are arrays of vectors, so will also work for a matrix.
1087 // Will use the access chain's 'component' for variable index into a vector.
1088
1089 // This adapter is building access chains left to right.
1090 // Set up the access chain to the left.
1091 node->getLeft()->traverse(this);
1092
1093 // save it so that computing the right side doesn't trash it
1094 spv::Builder::AccessChain partial = builder.getAccessChain();
1095
1096 // compute the next index in the chain
1097 builder.clearAccessChain();
1098 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001099 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
1101 // restore the saved access chain
1102 builder.setAccessChain(partial);
1103
1104 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001105 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001106 else
John Kessenichfa668da2015-09-13 14:46:30 -06001107 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001108 }
1109 return false;
1110 case glslang::EOpVectorSwizzle:
1111 {
1112 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001113 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001114 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001115 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001116 }
1117 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001118 case glslang::EOpMatrixSwizzle:
1119 logger->missingFunctionality("matrix swizzle");
1120 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001121 case glslang::EOpLogicalOr:
1122 case glslang::EOpLogicalAnd:
1123 {
1124
1125 // These may require short circuiting, but can sometimes be done as straight
1126 // binary operations. The right operand must be short circuited if it has
1127 // side effects, and should probably be if it is complex.
1128 if (isTrivial(node->getRight()->getAsTyped()))
1129 break; // handle below as a normal binary operation
1130 // otherwise, we need to do dynamic short circuiting on the right operand
1131 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1132 builder.clearAccessChain();
1133 builder.setAccessChainRValue(result);
1134 }
1135 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001136 default:
1137 break;
1138 }
1139
1140 // Assume generic binary op...
1141
John Kessenich32cfd492016-02-02 12:37:46 -07001142 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001143 builder.clearAccessChain();
1144 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001145 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001146
John Kessenich32cfd492016-02-02 12:37:46 -07001147 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001148 builder.clearAccessChain();
1149 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001150 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001151
John Kessenich32cfd492016-02-02 12:37:46 -07001152 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001153 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001154 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001155 convertGlslangToSpvType(node->getType()), left, right,
1156 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001157
John Kessenich50e57562015-12-21 21:21:11 -07001158 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001159 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001160 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001161 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001162 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001163 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001164 return false;
1165 }
John Kessenich140f3df2015-06-26 16:58:36 -06001166}
1167
1168bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1169{
qining40887662016-04-03 22:20:42 -04001170 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1171 if (node->getType().getQualifier().isSpecConstant())
1172 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1173
John Kessenichfc51d282015-08-19 13:34:18 -06001174 spv::Id result = spv::NoResult;
1175
1176 // try texturing first
1177 result = createImageTextureFunctionCall(node);
1178 if (result != spv::NoResult) {
1179 builder.clearAccessChain();
1180 builder.setAccessChainRValue(result);
1181
1182 return false; // done with this node
1183 }
1184
1185 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001186
1187 if (node->getOp() == glslang::EOpArrayLength) {
1188 // Quite special; won't want to evaluate the operand.
1189
1190 // Normal .length() would have been constant folded by the front-end.
1191 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001192 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001193 assert(node->getOperand()->getType().isRuntimeSizedArray());
1194 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1195 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001196 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1197 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001198
1199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(length);
1201
1202 return false;
1203 }
1204
John Kessenichfc51d282015-08-19 13:34:18 -06001205 // Start by evaluating the operand
1206
John Kessenich8c8505c2016-07-26 12:50:38 -06001207 // Does it need a swizzle inversion? If so, evaluation is inverted;
1208 // operate first on the swizzle base, then apply the swizzle.
1209 spv::Id invertedType = spv::NoType;
1210 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1211 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1212 invertedType = getInvertedSwizzleType(*node->getOperand());
1213
John Kessenich140f3df2015-06-26 16:58:36 -06001214 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001215 if (invertedType != spv::NoType)
1216 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1217 else
1218 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001219
Rex Xufc618912015-09-09 16:42:49 +08001220 spv::Id operand = spv::NoResult;
1221
1222 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1223 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001224 node->getOp() == glslang::EOpAtomicCounter ||
1225 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001226 operand = builder.accessChainGetLValue(); // Special case l-value operands
1227 else
John Kessenich32cfd492016-02-02 12:37:46 -07001228 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001229
John Kessenichf6640762016-08-01 19:44:00 -06001230 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001231 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001232
1233 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001234 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001236
1237 // if not, then possibly an operation
1238 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001239 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001240
1241 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001242 if (invertedType)
1243 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1244
John Kessenich140f3df2015-06-26 16:58:36 -06001245 builder.clearAccessChain();
1246 builder.setAccessChainRValue(result);
1247
1248 return false; // done with this node
1249 }
1250
1251 // it must be a special case, check...
1252 switch (node->getOp()) {
1253 case glslang::EOpPostIncrement:
1254 case glslang::EOpPostDecrement:
1255 case glslang::EOpPreIncrement:
1256 case glslang::EOpPreDecrement:
1257 {
1258 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001259 spv::Id one = 0;
1260 if (node->getBasicType() == glslang::EbtFloat)
1261 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001262 else if (node->getBasicType() == glslang::EbtDouble)
1263 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001264#ifdef AMD_EXTENSIONS
1265 else if (node->getBasicType() == glslang::EbtFloat16)
1266 one = builder.makeFloat16Constant(1.0F);
1267#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001268 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1269 one = builder.makeInt64Constant(1);
1270 else
1271 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001272 glslang::TOperator op;
1273 if (node->getOp() == glslang::EOpPreIncrement ||
1274 node->getOp() == glslang::EOpPostIncrement)
1275 op = glslang::EOpAdd;
1276 else
1277 op = glslang::EOpSub;
1278
John Kessenichf6640762016-08-01 19:44:00 -06001279 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001280 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001281 convertGlslangToSpvType(node->getType()), operand, one,
1282 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001283 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001284
1285 // The result of operation is always stored, but conditionally the
1286 // consumed result. The consumed result is always an r-value.
1287 builder.accessChainStore(result);
1288 builder.clearAccessChain();
1289 if (node->getOp() == glslang::EOpPreIncrement ||
1290 node->getOp() == glslang::EOpPreDecrement)
1291 builder.setAccessChainRValue(result);
1292 else
1293 builder.setAccessChainRValue(operand);
1294 }
1295
1296 return false;
1297
1298 case glslang::EOpEmitStreamVertex:
1299 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1300 return false;
1301 case glslang::EOpEndStreamPrimitive:
1302 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1303 return false;
1304
1305 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001306 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001307 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001308 }
John Kessenich140f3df2015-06-26 16:58:36 -06001309}
1310
1311bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1312{
qining27e04a02016-04-14 16:40:20 -04001313 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1314 if (node->getType().getQualifier().isSpecConstant())
1315 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1316
John Kessenichfc51d282015-08-19 13:34:18 -06001317 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001318 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1319 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001320
1321 // try texturing
1322 result = createImageTextureFunctionCall(node);
1323 if (result != spv::NoResult) {
1324 builder.clearAccessChain();
1325 builder.setAccessChainRValue(result);
1326
1327 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001328 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001329 // "imageStore" is a special case, which has no result
1330 return false;
1331 }
John Kessenichfc51d282015-08-19 13:34:18 -06001332
John Kessenich140f3df2015-06-26 16:58:36 -06001333 glslang::TOperator binOp = glslang::EOpNull;
1334 bool reduceComparison = true;
1335 bool isMatrix = false;
1336 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001337 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 assert(node->getOp());
1340
John Kessenichf6640762016-08-01 19:44:00 -06001341 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001342
1343 switch (node->getOp()) {
1344 case glslang::EOpSequence:
1345 {
1346 if (preVisit)
1347 ++sequenceDepth;
1348 else
1349 --sequenceDepth;
1350
1351 if (sequenceDepth == 1) {
1352 // If this is the parent node of all the functions, we want to see them
1353 // early, so all call points have actual SPIR-V functions to reference.
1354 // In all cases, still let the traverser visit the children for us.
1355 makeFunctions(node->getAsAggregate()->getSequence());
1356
John Kessenich6fccb3c2016-09-19 16:01:41 -06001357 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001358 // anything else gets there, so visit out of order, doing them all now.
1359 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1360
John Kessenich6a60c2f2016-12-08 21:01:59 -07001361 // 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 -06001362 // so do them manually.
1363 visitFunctions(node->getAsAggregate()->getSequence());
1364
1365 return false;
1366 }
1367
1368 return true;
1369 }
1370 case glslang::EOpLinkerObjects:
1371 {
1372 if (visit == glslang::EvPreVisit)
1373 linkageOnly = true;
1374 else
1375 linkageOnly = false;
1376
1377 return true;
1378 }
1379 case glslang::EOpComma:
1380 {
1381 // processing from left to right naturally leaves the right-most
1382 // lying around in the access chain
1383 glslang::TIntermSequence& glslangOperands = node->getSequence();
1384 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1385 glslangOperands[i]->traverse(this);
1386
1387 return false;
1388 }
1389 case glslang::EOpFunction:
1390 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001391 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001392 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001393 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001394 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001395 } else {
1396 handleFunctionEntry(node);
1397 }
1398 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001399 if (inEntryPoint)
1400 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001401 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001402 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001403 }
1404
1405 return true;
1406 case glslang::EOpParameters:
1407 // Parameters will have been consumed by EOpFunction processing, but not
1408 // the body, so we still visited the function node's children, making this
1409 // child redundant.
1410 return false;
1411 case glslang::EOpFunctionCall:
1412 {
1413 if (node->isUserDefined())
1414 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001415 // 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 -07001416 if (result) {
1417 builder.clearAccessChain();
1418 builder.setAccessChainRValue(result);
1419 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001420 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001421
1422 return false;
1423 }
1424 case glslang::EOpConstructMat2x2:
1425 case glslang::EOpConstructMat2x3:
1426 case glslang::EOpConstructMat2x4:
1427 case glslang::EOpConstructMat3x2:
1428 case glslang::EOpConstructMat3x3:
1429 case glslang::EOpConstructMat3x4:
1430 case glslang::EOpConstructMat4x2:
1431 case glslang::EOpConstructMat4x3:
1432 case glslang::EOpConstructMat4x4:
1433 case glslang::EOpConstructDMat2x2:
1434 case glslang::EOpConstructDMat2x3:
1435 case glslang::EOpConstructDMat2x4:
1436 case glslang::EOpConstructDMat3x2:
1437 case glslang::EOpConstructDMat3x3:
1438 case glslang::EOpConstructDMat3x4:
1439 case glslang::EOpConstructDMat4x2:
1440 case glslang::EOpConstructDMat4x3:
1441 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001442#ifdef AMD_EXTENSIONS
1443 case glslang::EOpConstructF16Mat2x2:
1444 case glslang::EOpConstructF16Mat2x3:
1445 case glslang::EOpConstructF16Mat2x4:
1446 case glslang::EOpConstructF16Mat3x2:
1447 case glslang::EOpConstructF16Mat3x3:
1448 case glslang::EOpConstructF16Mat3x4:
1449 case glslang::EOpConstructF16Mat4x2:
1450 case glslang::EOpConstructF16Mat4x3:
1451 case glslang::EOpConstructF16Mat4x4:
1452#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001453 isMatrix = true;
1454 // fall through
1455 case glslang::EOpConstructFloat:
1456 case glslang::EOpConstructVec2:
1457 case glslang::EOpConstructVec3:
1458 case glslang::EOpConstructVec4:
1459 case glslang::EOpConstructDouble:
1460 case glslang::EOpConstructDVec2:
1461 case glslang::EOpConstructDVec3:
1462 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001463#ifdef AMD_EXTENSIONS
1464 case glslang::EOpConstructFloat16:
1465 case glslang::EOpConstructF16Vec2:
1466 case glslang::EOpConstructF16Vec3:
1467 case glslang::EOpConstructF16Vec4:
1468#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001469 case glslang::EOpConstructBool:
1470 case glslang::EOpConstructBVec2:
1471 case glslang::EOpConstructBVec3:
1472 case glslang::EOpConstructBVec4:
1473 case glslang::EOpConstructInt:
1474 case glslang::EOpConstructIVec2:
1475 case glslang::EOpConstructIVec3:
1476 case glslang::EOpConstructIVec4:
1477 case glslang::EOpConstructUint:
1478 case glslang::EOpConstructUVec2:
1479 case glslang::EOpConstructUVec3:
1480 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001481 case glslang::EOpConstructInt64:
1482 case glslang::EOpConstructI64Vec2:
1483 case glslang::EOpConstructI64Vec3:
1484 case glslang::EOpConstructI64Vec4:
1485 case glslang::EOpConstructUint64:
1486 case glslang::EOpConstructU64Vec2:
1487 case glslang::EOpConstructU64Vec3:
1488 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001489 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001490 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001491 {
1492 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001493 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001494 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001495 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001496 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001497 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001498 std::vector<spv::Id> constituents;
1499 for (int c = 0; c < (int)arguments.size(); ++c)
1500 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001501 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001502 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001503 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001504 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001505 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001506
1507 builder.clearAccessChain();
1508 builder.setAccessChainRValue(constructed);
1509
1510 return false;
1511 }
1512
1513 // These six are component-wise compares with component-wise results.
1514 // Forward on to createBinaryOperation(), requesting a vector result.
1515 case glslang::EOpLessThan:
1516 case glslang::EOpGreaterThan:
1517 case glslang::EOpLessThanEqual:
1518 case glslang::EOpGreaterThanEqual:
1519 case glslang::EOpVectorEqual:
1520 case glslang::EOpVectorNotEqual:
1521 {
1522 // Map the operation to a binary
1523 binOp = node->getOp();
1524 reduceComparison = false;
1525 switch (node->getOp()) {
1526 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1527 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1528 default: binOp = node->getOp(); break;
1529 }
1530
1531 break;
1532 }
1533 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001534 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001535 binOp = glslang::EOpMul;
1536 break;
1537 case glslang::EOpOuterProduct:
1538 // two vectors multiplied to make a matrix
1539 binOp = glslang::EOpOuterProduct;
1540 break;
1541 case glslang::EOpDot:
1542 {
qining25262b32016-05-06 17:25:16 -04001543 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001544 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001545 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001546 binOp = glslang::EOpMul;
1547 break;
1548 }
1549 case glslang::EOpMod:
1550 // when an aggregate, this is the floating-point mod built-in function,
1551 // which can be emitted by the one in createBinaryOperation()
1552 binOp = glslang::EOpMod;
1553 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001554 case glslang::EOpEmitVertex:
1555 case glslang::EOpEndPrimitive:
1556 case glslang::EOpBarrier:
1557 case glslang::EOpMemoryBarrier:
1558 case glslang::EOpMemoryBarrierAtomicCounter:
1559 case glslang::EOpMemoryBarrierBuffer:
1560 case glslang::EOpMemoryBarrierImage:
1561 case glslang::EOpMemoryBarrierShared:
1562 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001563 case glslang::EOpAllMemoryBarrierWithGroupSync:
1564 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1565 case glslang::EOpWorkgroupMemoryBarrier:
1566 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001567 noReturnValue = true;
1568 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1569 break;
1570
John Kessenich426394d2015-07-23 10:22:48 -06001571 case glslang::EOpAtomicAdd:
1572 case glslang::EOpAtomicMin:
1573 case glslang::EOpAtomicMax:
1574 case glslang::EOpAtomicAnd:
1575 case glslang::EOpAtomicOr:
1576 case glslang::EOpAtomicXor:
1577 case glslang::EOpAtomicExchange:
1578 case glslang::EOpAtomicCompSwap:
1579 atomic = true;
1580 break;
1581
John Kessenich140f3df2015-06-26 16:58:36 -06001582 default:
1583 break;
1584 }
1585
1586 //
1587 // See if it maps to a regular operation.
1588 //
John Kessenich140f3df2015-06-26 16:58:36 -06001589 if (binOp != glslang::EOpNull) {
1590 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1591 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1592 assert(left && right);
1593
1594 builder.clearAccessChain();
1595 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001596 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001597
1598 builder.clearAccessChain();
1599 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001600 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001601
qining25262b32016-05-06 17:25:16 -04001602 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001603 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001604 left->getType().getBasicType(), reduceComparison);
1605
1606 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001607 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001608 builder.clearAccessChain();
1609 builder.setAccessChainRValue(result);
1610
1611 return false;
1612 }
1613
John Kessenich426394d2015-07-23 10:22:48 -06001614 //
1615 // Create the list of operands.
1616 //
John Kessenich140f3df2015-06-26 16:58:36 -06001617 glslang::TIntermSequence& glslangOperands = node->getSequence();
1618 std::vector<spv::Id> operands;
1619 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001620 // special case l-value operands; there are just a few
1621 bool lvalue = false;
1622 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001623 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001624 case glslang::EOpModf:
1625 if (arg == 1)
1626 lvalue = true;
1627 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001628 case glslang::EOpInterpolateAtSample:
1629 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001630#ifdef AMD_EXTENSIONS
1631 case glslang::EOpInterpolateAtVertex:
1632#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001633 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001634 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001635
1636 // Does it need a swizzle inversion? If so, evaluation is inverted;
1637 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001638 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001639 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1640 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1641 }
Rex Xu7a26c172015-12-08 17:12:09 +08001642 break;
Rex Xud4782c12015-09-06 16:30:11 +08001643 case glslang::EOpAtomicAdd:
1644 case glslang::EOpAtomicMin:
1645 case glslang::EOpAtomicMax:
1646 case glslang::EOpAtomicAnd:
1647 case glslang::EOpAtomicOr:
1648 case glslang::EOpAtomicXor:
1649 case glslang::EOpAtomicExchange:
1650 case glslang::EOpAtomicCompSwap:
1651 if (arg == 0)
1652 lvalue = true;
1653 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001654 case glslang::EOpAddCarry:
1655 case glslang::EOpSubBorrow:
1656 if (arg == 2)
1657 lvalue = true;
1658 break;
1659 case glslang::EOpUMulExtended:
1660 case glslang::EOpIMulExtended:
1661 if (arg >= 2)
1662 lvalue = true;
1663 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001664 default:
1665 break;
1666 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001667 builder.clearAccessChain();
1668 if (invertedType != spv::NoType && arg == 0)
1669 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1670 else
1671 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001672 if (lvalue)
1673 operands.push_back(builder.accessChainGetLValue());
1674 else
John Kessenich32cfd492016-02-02 12:37:46 -07001675 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001676 }
John Kessenich426394d2015-07-23 10:22:48 -06001677
1678 if (atomic) {
1679 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001680 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001681 } else {
1682 // Pass through to generic operations.
1683 switch (glslangOperands.size()) {
1684 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001685 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001686 break;
1687 case 1:
qining25262b32016-05-06 17:25:16 -04001688 result = createUnaryOperation(
1689 node->getOp(), precision,
1690 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001691 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001692 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001693 break;
1694 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001695 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001696 break;
1697 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001698 if (invertedType)
1699 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 if (noReturnValue)
1703 return false;
1704
1705 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001706 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001707 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001708 } else {
1709 builder.clearAccessChain();
1710 builder.setAccessChainRValue(result);
1711 return false;
1712 }
1713}
1714
1715bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1716{
1717 // This path handles both if-then-else and ?:
1718 // The if-then-else has a node type of void, while
1719 // ?: has a non-void node type
1720 spv::Id result = 0;
1721 if (node->getBasicType() != glslang::EbtVoid) {
1722 // don't handle this as just on-the-fly temporaries, because there will be two names
1723 // and better to leave SSA to later passes
1724 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1725 }
1726
1727 // emit the condition before doing anything with selection
1728 node->getCondition()->traverse(this);
1729
1730 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001731 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001732
1733 if (node->getTrueBlock()) {
1734 // emit the "then" statement
1735 node->getTrueBlock()->traverse(this);
1736 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001737 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001738 }
1739
1740 if (node->getFalseBlock()) {
1741 ifBuilder.makeBeginElse();
1742 // emit the "else" statement
1743 node->getFalseBlock()->traverse(this);
1744 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001745 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001746 }
1747
1748 ifBuilder.makeEndIf();
1749
1750 if (result) {
1751 // GLSL only has r-values as the result of a :?, but
1752 // if we have an l-value, that can be more efficient if it will
1753 // become the base of a complex r-value expression, because the
1754 // next layer copies r-values into memory to use the access-chain mechanism
1755 builder.clearAccessChain();
1756 builder.setAccessChainLValue(result);
1757 }
1758
1759 return false;
1760}
1761
1762bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1763{
1764 // emit and get the condition before doing anything with switch
1765 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001766 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001767
1768 // browse the children to sort out code segments
1769 int defaultSegment = -1;
1770 std::vector<TIntermNode*> codeSegments;
1771 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1772 std::vector<int> caseValues;
1773 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1774 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1775 TIntermNode* child = *c;
1776 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001777 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001778 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001779 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001780 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1781 } else
1782 codeSegments.push_back(child);
1783 }
1784
qining25262b32016-05-06 17:25:16 -04001785 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001786 // statements between the last case and the end of the switch statement
1787 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1788 (int)codeSegments.size() == defaultSegment)
1789 codeSegments.push_back(nullptr);
1790
1791 // make the switch statement
1792 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001793 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001794
1795 // emit all the code in the segments
1796 breakForLoop.push(false);
1797 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1798 builder.nextSwitchSegment(segmentBlocks, s);
1799 if (codeSegments[s])
1800 codeSegments[s]->traverse(this);
1801 else
1802 builder.addSwitchBreak();
1803 }
1804 breakForLoop.pop();
1805
1806 builder.endSwitch(segmentBlocks);
1807
1808 return false;
1809}
1810
1811void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1812{
1813 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001814 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001815
1816 builder.clearAccessChain();
1817 builder.setAccessChainRValue(constant);
1818}
1819
1820bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1821{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001822 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001823 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001824 // Spec requires back edges to target header blocks, and every header block
1825 // must dominate its merge block. Make a header block first to ensure these
1826 // conditions are met. By definition, it will contain OpLoopMerge, followed
1827 // by a block-ending branch. But we don't want to put any other body/test
1828 // instructions in it, since the body/test may have arbitrary instructions,
1829 // including merges of its own.
1830 builder.setBuildPoint(&blocks.head);
1831 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001832 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001833 spv::Block& test = builder.makeNewBlock();
1834 builder.createBranch(&test);
1835
1836 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001837 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001838 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001839 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001840 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1841
1842 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001843 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001844 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001845 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001846 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001847 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001848
1849 builder.setBuildPoint(&blocks.continue_target);
1850 if (node->getTerminal())
1851 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001852 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001853 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001854 builder.createBranch(&blocks.body);
1855
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001856 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001857 builder.setBuildPoint(&blocks.body);
1858 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001859 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001860 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001861 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001862
1863 builder.setBuildPoint(&blocks.continue_target);
1864 if (node->getTerminal())
1865 node->getTerminal()->traverse(this);
1866 if (node->getTest()) {
1867 node->getTest()->traverse(this);
1868 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001869 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001870 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001871 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001872 // TODO: unless there was a break/return/discard instruction
1873 // somewhere in the body, this is an infinite loop, so we should
1874 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001875 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001876 }
John Kessenich140f3df2015-06-26 16:58:36 -06001877 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001878 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001879 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001880 return false;
1881}
1882
1883bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1884{
1885 if (node->getExpression())
1886 node->getExpression()->traverse(this);
1887
1888 switch (node->getFlowOp()) {
1889 case glslang::EOpKill:
1890 builder.makeDiscard();
1891 break;
1892 case glslang::EOpBreak:
1893 if (breakForLoop.top())
1894 builder.createLoopExit();
1895 else
1896 builder.addSwitchBreak();
1897 break;
1898 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001899 builder.createLoopContinue();
1900 break;
1901 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001902 if (node->getExpression()) {
1903 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1904 spv::Id returnId = accessChainLoad(glslangReturnType);
1905 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1906 builder.clearAccessChain();
1907 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1908 builder.setAccessChainLValue(copyId);
1909 multiTypeStore(glslangReturnType, returnId);
1910 returnId = builder.createLoad(copyId);
1911 }
1912 builder.makeReturn(false, returnId);
1913 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001914 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001915
1916 builder.clearAccessChain();
1917 break;
1918
1919 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001920 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001921 break;
1922 }
1923
1924 return false;
1925}
1926
1927spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1928{
qining25262b32016-05-06 17:25:16 -04001929 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001930 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001931 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001932 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001933 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001934 }
1935
1936 // Now, handle actual variables
1937 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1938 spv::Id spvType = convertGlslangToSpvType(node->getType());
1939
1940 const char* name = node->getName().c_str();
1941 if (glslang::IsAnonymous(name))
1942 name = "";
1943
1944 return builder.createVariable(storageClass, spvType, name);
1945}
1946
1947// Return type Id of the sampled type.
1948spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1949{
1950 switch (sampler.type) {
1951 case glslang::EbtFloat: return builder.makeFloatType(32);
1952 case glslang::EbtInt: return builder.makeIntType(32);
1953 case glslang::EbtUint: return builder.makeUintType(32);
1954 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001955 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001956 return builder.makeFloatType(32);
1957 }
1958}
1959
John Kessenich8c8505c2016-07-26 12:50:38 -06001960// If node is a swizzle operation, return the type that should be used if
1961// the swizzle base is first consumed by another operation, before the swizzle
1962// is applied.
1963spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1964{
John Kessenichecba76f2017-01-06 00:34:48 -07001965 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001966 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1967 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1968 else
1969 return spv::NoType;
1970}
1971
1972// When inverting a swizzle with a parent op, this function
1973// will apply the swizzle operation to a completed parent operation.
1974spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1975{
1976 std::vector<unsigned> swizzle;
1977 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1978 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1979}
1980
John Kessenich8c8505c2016-07-26 12:50:38 -06001981// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1982void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1983{
1984 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1985 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1986 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1987}
1988
John Kessenich3ac051e2015-12-20 11:29:16 -07001989// Convert from a glslang type to an SPV type, by calling into a
1990// recursive version of this function. This establishes the inherited
1991// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001992spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1993{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001994 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001995}
1996
1997// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001998// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001999// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002000spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002001{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002002 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002003
2004 switch (type.getBasicType()) {
2005 case glslang::EbtVoid:
2006 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002007 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002008 break;
2009 case glslang::EbtFloat:
2010 spvType = builder.makeFloatType(32);
2011 break;
2012 case glslang::EbtDouble:
2013 spvType = builder.makeFloatType(64);
2014 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002015#ifdef AMD_EXTENSIONS
2016 case glslang::EbtFloat16:
2017 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002018 spvType = builder.makeFloatType(16);
2019 break;
2020#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002021 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002022 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2023 // a 32-bit int where non-0 means true.
2024 if (explicitLayout != glslang::ElpNone)
2025 spvType = builder.makeUintType(32);
2026 else
2027 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002028 break;
2029 case glslang::EbtInt:
2030 spvType = builder.makeIntType(32);
2031 break;
2032 case glslang::EbtUint:
2033 spvType = builder.makeUintType(32);
2034 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002035 case glslang::EbtInt64:
2036 builder.addCapability(spv::CapabilityInt64);
2037 spvType = builder.makeIntType(64);
2038 break;
2039 case glslang::EbtUint64:
2040 builder.addCapability(spv::CapabilityInt64);
2041 spvType = builder.makeUintType(64);
2042 break;
John Kessenich426394d2015-07-23 10:22:48 -06002043 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002044 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002045 spvType = builder.makeUintType(32);
2046 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002047 case glslang::EbtSampler:
2048 {
2049 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002050 if (sampler.sampler) {
2051 // pure sampler
2052 spvType = builder.makeSamplerType();
2053 } else {
2054 // an image is present, make its type
2055 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2056 sampler.image ? 2 : 1, TranslateImageFormat(type));
2057 if (sampler.combined) {
2058 // already has both image and sampler, make the combined type
2059 spvType = builder.makeSampledImageType(spvType);
2060 }
John Kessenich55e7d112015-11-15 21:33:39 -07002061 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002062 }
John Kessenich140f3df2015-06-26 16:58:36 -06002063 break;
2064 case glslang::EbtStruct:
2065 case glslang::EbtBlock:
2066 {
2067 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002068 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002069
2070 // Try to share structs for different layouts, but not yet for other
2071 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002072 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002073 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002074 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002075 break;
2076
2077 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002078 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002079 memberRemapper[glslangMembers].resize(glslangMembers->size());
2080 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002081 }
2082 break;
2083 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002084 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002085 break;
2086 }
2087
2088 if (type.isMatrix())
2089 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2090 else {
2091 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2092 if (type.getVectorSize() > 1)
2093 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2094 }
2095
2096 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002097 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2098
John Kessenichc9a80832015-09-12 12:17:44 -06002099 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002100 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002101 // We need to decorate array strides for types needing explicit layout, except blocks.
2102 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002103 // Use a dummy glslang type for querying internal strides of
2104 // arrays of arrays, but using just a one-dimensional array.
2105 glslang::TType simpleArrayType(type, 0); // deference type of the array
2106 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2107 simpleArrayType.getArraySizes().dereference();
2108
2109 // Will compute the higher-order strides here, rather than making a whole
2110 // pile of types and doing repetitive recursion on their contents.
2111 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2112 }
John Kessenichf8842e52016-01-04 19:22:56 -07002113
2114 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002115 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002116 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002117 if (stride > 0)
2118 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002119 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002120 }
2121 } else {
2122 // single-dimensional array, and don't yet have stride
2123
John Kessenichf8842e52016-01-04 19:22:56 -07002124 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002125 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2126 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002127 }
John Kessenich31ed4832015-09-09 17:51:38 -06002128
John Kessenichc9a80832015-09-12 12:17:44 -06002129 // Do the outer dimension, which might not be known for a runtime-sized array
2130 if (type.isRuntimeSizedArray()) {
2131 spvType = builder.makeRuntimeArray(spvType);
2132 } else {
2133 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002134 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002135 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002136 if (stride > 0)
2137 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002138 }
2139
2140 return spvType;
2141}
2142
John Kessenich6090df02016-06-30 21:18:02 -06002143// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2144// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2145// Mutually recursive with convertGlslangToSpvType().
2146spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2147 const glslang::TTypeList* glslangMembers,
2148 glslang::TLayoutPacking explicitLayout,
2149 const glslang::TQualifier& qualifier)
2150{
2151 // Create a vector of struct types for SPIR-V to consume
2152 std::vector<spv::Id> spvMembers;
2153 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2154 int locationOffset = 0; // for use across struct members, when they are called recursively
2155 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2156 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2157 if (glslangMember.hiddenMember()) {
2158 ++memberDelta;
2159 if (type.getBasicType() == glslang::EbtBlock)
2160 memberRemapper[glslangMembers][i] = -1;
2161 } else {
2162 if (type.getBasicType() == glslang::EbtBlock)
2163 memberRemapper[glslangMembers][i] = i - memberDelta;
2164 // modify just this child's view of the qualifier
2165 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2166 InheritQualifiers(memberQualifier, qualifier);
2167
2168 // manually inherit location; it's more complex
2169 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2170 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2171 if (qualifier.hasLocation())
2172 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2173
2174 // recurse
2175 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2176 }
2177 }
2178
2179 // Make the SPIR-V type
2180 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002181 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002182 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2183
2184 // Decorate it
2185 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2186
2187 return spvType;
2188}
2189
2190void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2191 const glslang::TTypeList* glslangMembers,
2192 glslang::TLayoutPacking explicitLayout,
2193 const glslang::TQualifier& qualifier,
2194 spv::Id spvType)
2195{
2196 // Name and decorate the non-hidden members
2197 int offset = -1;
2198 int locationOffset = 0; // for use within the members of this struct
2199 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2200 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2201 int member = i;
2202 if (type.getBasicType() == glslang::EbtBlock)
2203 member = memberRemapper[glslangMembers][i];
2204
2205 // modify just this child's view of the qualifier
2206 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2207 InheritQualifiers(memberQualifier, qualifier);
2208
2209 // using -1 above to indicate a hidden member
2210 if (member >= 0) {
2211 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2212 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2213 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2214 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2215 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2216 if (type.getBasicType() == glslang::EbtBlock) {
2217 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2218 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2219 }
2220 }
2221 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2222
2223 if (qualifier.storage == glslang::EvqBuffer) {
2224 std::vector<spv::Decoration> memory;
2225 TranslateMemoryDecoration(memberQualifier, memory);
2226 for (unsigned int i = 0; i < memory.size(); ++i)
2227 addMemberDecoration(spvType, member, memory[i]);
2228 }
2229
John Kessenich2f47bc92016-06-30 21:47:35 -06002230 // Compute location decoration; tricky based on whether inheritance is at play and
2231 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002232 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2233 // probably move to the linker stage of the front end proper, and just have the
2234 // answer sitting already distributed throughout the individual member locations.
2235 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002236 // Ignore member locations if the container is an array, as that's
2237 // ill-specified and decisions have been made to not allow this anyway.
2238 // The object itself must have a location, and that comes out from decorating the object,
2239 // not the type (this code decorates types).
2240 if (! type.isArray()) {
2241 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2242 // struct members should not have explicit locations
2243 assert(type.getBasicType() != glslang::EbtStruct);
2244 location = memberQualifier.layoutLocation;
2245 } else if (type.getBasicType() != glslang::EbtBlock) {
2246 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2247 // The members, and their nested types, must not themselves have Location decorations.
2248 } else if (qualifier.hasLocation()) // inheritance
2249 location = qualifier.layoutLocation + locationOffset;
2250 }
John Kessenich6090df02016-06-30 21:18:02 -06002251 if (location >= 0)
2252 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2253
John Kessenich2f47bc92016-06-30 21:47:35 -06002254 if (qualifier.hasLocation()) // track for upcoming inheritance
2255 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2256
John Kessenich6090df02016-06-30 21:18:02 -06002257 // component, XFB, others
2258 if (glslangMember.getQualifier().hasComponent())
2259 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2260 if (glslangMember.getQualifier().hasXfbOffset())
2261 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2262 else if (explicitLayout != glslang::ElpNone) {
2263 // figure out what to do with offset, which is accumulating
2264 int nextOffset;
2265 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2266 if (offset >= 0)
2267 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2268 offset = nextOffset;
2269 }
2270
2271 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2272 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2273
2274 // built-in variable decorations
2275 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002276 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002277 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2278 }
2279 }
2280
2281 // Decorate the structure
2282 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2283 addDecoration(spvType, TranslateBlockDecoration(type));
2284 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2285 builder.addCapability(spv::CapabilityGeometryStreams);
2286 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2287 }
2288 if (glslangIntermediate->getXfbMode()) {
2289 builder.addCapability(spv::CapabilityTransformFeedback);
2290 if (type.getQualifier().hasXfbStride())
2291 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2292 if (type.getQualifier().hasXfbBuffer())
2293 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2294 }
2295}
2296
John Kessenich6c292d32016-02-15 20:58:50 -07002297// Turn the expression forming the array size into an id.
2298// This is not quite trivial, because of specialization constants.
2299// Sometimes, a raw constant is turned into an Id, and sometimes
2300// a specialization constant expression is.
2301spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2302{
2303 // First, see if this is sized with a node, meaning a specialization constant:
2304 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2305 if (specNode != nullptr) {
2306 builder.clearAccessChain();
2307 specNode->traverse(this);
2308 return accessChainLoad(specNode->getAsTyped()->getType());
2309 }
qining25262b32016-05-06 17:25:16 -04002310
John Kessenich6c292d32016-02-15 20:58:50 -07002311 // Otherwise, need a compile-time (front end) size, get it:
2312 int size = arraySizes.getDimSize(dim);
2313 assert(size > 0);
2314 return builder.makeUintConstant(size);
2315}
2316
John Kessenich103bef92016-02-08 21:38:15 -07002317// Wrap the builder's accessChainLoad to:
2318// - localize handling of RelaxedPrecision
2319// - use the SPIR-V inferred type instead of another conversion of the glslang type
2320// (avoids unnecessary work and possible type punning for structures)
2321// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002322spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2323{
John Kessenich103bef92016-02-08 21:38:15 -07002324 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2325 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2326
2327 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002328 if (type.getBasicType() == glslang::EbtBool) {
2329 if (builder.isScalarType(nominalTypeId)) {
2330 // Conversion for bool
2331 spv::Id boolType = builder.makeBoolType();
2332 if (nominalTypeId != boolType)
2333 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2334 } else if (builder.isVectorType(nominalTypeId)) {
2335 // Conversion for bvec
2336 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2337 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2338 if (nominalTypeId != bvecType)
2339 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2340 }
2341 }
John Kessenich103bef92016-02-08 21:38:15 -07002342
2343 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002344}
2345
Rex Xu27253232016-02-23 17:51:09 +08002346// Wrap the builder's accessChainStore to:
2347// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002348//
2349// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002350void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2351{
2352 // Need to convert to abstract types when necessary
2353 if (type.getBasicType() == glslang::EbtBool) {
2354 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2355
2356 if (builder.isScalarType(nominalTypeId)) {
2357 // Conversion for bool
2358 spv::Id boolType = builder.makeBoolType();
2359 if (nominalTypeId != boolType) {
2360 spv::Id zero = builder.makeUintConstant(0);
2361 spv::Id one = builder.makeUintConstant(1);
2362 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2363 }
2364 } else if (builder.isVectorType(nominalTypeId)) {
2365 // Conversion for bvec
2366 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2367 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2368 if (nominalTypeId != bvecType) {
2369 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2370 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2371 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2372 }
2373 }
2374 }
2375
2376 builder.accessChainStore(rvalue);
2377}
2378
John Kessenich4bf71552016-09-02 11:20:21 -06002379// For storing when types match at the glslang level, but not might match at the
2380// SPIR-V level.
2381//
2382// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002383// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002384// as in a member-decorated way.
2385//
2386// NOTE: This function can handle any store request; if it's not special it
2387// simplifies to a simple OpStore.
2388//
2389// Implicitly uses the existing builder.accessChain as the storage target.
2390void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2391{
John Kessenichb3e24e42016-09-11 12:33:43 -06002392 // we only do the complex path here if it's an aggregate
2393 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002394 accessChainStore(type, rValue);
2395 return;
2396 }
2397
John Kessenichb3e24e42016-09-11 12:33:43 -06002398 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002399 spv::Id rType = builder.getTypeId(rValue);
2400 spv::Id lValue = builder.accessChainGetLValue();
2401 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2402 if (lType == rType) {
2403 accessChainStore(type, rValue);
2404 return;
2405 }
2406
John Kessenichb3e24e42016-09-11 12:33:43 -06002407 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002408 // where the two types were the same type in GLSL. This requires member
2409 // by member copy, recursively.
2410
John Kessenichb3e24e42016-09-11 12:33:43 -06002411 // If an array, copy element by element.
2412 if (type.isArray()) {
2413 glslang::TType glslangElementType(type, 0);
2414 spv::Id elementRType = builder.getContainedTypeId(rType);
2415 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2416 // get the source member
2417 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002418
John Kessenichb3e24e42016-09-11 12:33:43 -06002419 // set up the target storage
2420 builder.clearAccessChain();
2421 builder.setAccessChainLValue(lValue);
2422 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002423
John Kessenichb3e24e42016-09-11 12:33:43 -06002424 // store the member
2425 multiTypeStore(glslangElementType, elementRValue);
2426 }
2427 } else {
2428 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002429
John Kessenichb3e24e42016-09-11 12:33:43 -06002430 // loop over structure members
2431 const glslang::TTypeList& members = *type.getStruct();
2432 for (int m = 0; m < (int)members.size(); ++m) {
2433 const glslang::TType& glslangMemberType = *members[m].type;
2434
2435 // get the source member
2436 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2437 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2438
2439 // set up the target storage
2440 builder.clearAccessChain();
2441 builder.setAccessChainLValue(lValue);
2442 builder.accessChainPush(builder.makeIntConstant(m));
2443
2444 // store the member
2445 multiTypeStore(glslangMemberType, memberRValue);
2446 }
John Kessenich4bf71552016-09-02 11:20:21 -06002447 }
2448}
2449
John Kessenichf85e8062015-12-19 13:57:10 -07002450// Decide whether or not this type should be
2451// decorated with offsets and strides, and if so
2452// whether std140 or std430 rules should be applied.
2453glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002454{
John Kessenichf85e8062015-12-19 13:57:10 -07002455 // has to be a block
2456 if (type.getBasicType() != glslang::EbtBlock)
2457 return glslang::ElpNone;
2458
2459 // has to be a uniform or buffer block
2460 if (type.getQualifier().storage != glslang::EvqUniform &&
2461 type.getQualifier().storage != glslang::EvqBuffer)
2462 return glslang::ElpNone;
2463
2464 // return the layout to use
2465 switch (type.getQualifier().layoutPacking) {
2466 case glslang::ElpStd140:
2467 case glslang::ElpStd430:
2468 return type.getQualifier().layoutPacking;
2469 default:
2470 return glslang::ElpNone;
2471 }
John Kessenich31ed4832015-09-09 17:51:38 -06002472}
2473
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002474// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002475int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002476{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002477 int size;
John Kessenich49987892015-12-29 17:11:44 -07002478 int stride;
2479 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002480
2481 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002482}
2483
John Kessenich49987892015-12-29 17:11:44 -07002484// 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 -07002485// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002486int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002487{
John Kessenich49987892015-12-29 17:11:44 -07002488 glslang::TType elementType;
2489 elementType.shallowCopy(matrixType);
2490 elementType.clearArraySizes();
2491
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002492 int size;
John Kessenich49987892015-12-29 17:11:44 -07002493 int stride;
2494 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2495
2496 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002497}
2498
John Kessenich5e4b1242015-08-06 22:53:06 -06002499// Given a member type of a struct, realign the current offset for it, and compute
2500// the next (not yet aligned) offset for the next member, which will get aligned
2501// on the next call.
2502// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2503// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2504// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002505void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002506 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002507{
2508 // this will get a positive value when deemed necessary
2509 nextOffset = -1;
2510
John Kessenich5e4b1242015-08-06 22:53:06 -06002511 // override anything in currentOffset with user-set offset
2512 if (memberType.getQualifier().hasOffset())
2513 currentOffset = memberType.getQualifier().layoutOffset;
2514
2515 // It could be that current linker usage in glslang updated all the layoutOffset,
2516 // in which case the following code does not matter. But, that's not quite right
2517 // once cross-compilation unit GLSL validation is done, as the original user
2518 // settings are needed in layoutOffset, and then the following will come into play.
2519
John Kessenichf85e8062015-12-19 13:57:10 -07002520 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002521 if (! memberType.getQualifier().hasOffset())
2522 currentOffset = -1;
2523
2524 return;
2525 }
2526
John Kessenichf85e8062015-12-19 13:57:10 -07002527 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002528 if (currentOffset < 0)
2529 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002530
John Kessenich5e4b1242015-08-06 22:53:06 -06002531 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2532 // but possibly not yet correctly aligned.
2533
2534 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002535 int dummyStride;
2536 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002537 glslang::RoundToPow2(currentOffset, memberAlignment);
2538 nextOffset = currentOffset + memberSize;
2539}
2540
David Netoa901ffe2016-06-08 14:11:40 +01002541void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002542{
David Netoa901ffe2016-06-08 14:11:40 +01002543 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2544 switch (glslangBuiltIn)
2545 {
2546 case glslang::EbvClipDistance:
2547 case glslang::EbvCullDistance:
2548 case glslang::EbvPointSize:
2549 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2550 // Alternately, we could just call this for any glslang built-in, since the
2551 // capability already guards against duplicates.
2552 TranslateBuiltInDecoration(glslangBuiltIn, false);
2553 break;
2554 default:
2555 // Capabilities were already generated when the struct was declared.
2556 break;
2557 }
John Kessenichebb50532016-05-16 19:22:05 -06002558}
2559
John Kessenich6fccb3c2016-09-19 16:01:41 -06002560bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002561{
John Kessenicheee9d532016-09-19 18:09:30 -06002562 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002563}
2564
2565// Make all the functions, skeletally, without actually visiting their bodies.
2566void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2567{
2568 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2569 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002570 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002571 continue;
2572
2573 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002574 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002575 //
qining25262b32016-05-06 17:25:16 -04002576 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002577 // function. What it is an address of varies:
2578 //
John Kessenich4bf71552016-09-02 11:20:21 -06002579 // - "in" parameters not marked as "const" can be written to without modifying the calling
2580 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002581 //
2582 // - "const in" parameters can just be the r-value, as no writes need occur.
2583 //
John Kessenich4bf71552016-09-02 11:20:21 -06002584 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2585 // 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 -06002586
2587 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002588 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2590
2591 for (int p = 0; p < (int)parameters.size(); ++p) {
2592 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2593 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002594 if (paramType.isOpaque())
2595 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2596 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002597 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2598 else
John Kessenich4bf71552016-09-02 11:20:21 -06002599 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002600 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002601 paramTypes.push_back(typeId);
2602 }
2603
2604 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002605 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2606 convertGlslangToSpvType(glslFunction->getType()),
2607 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002608
2609 // Track function to emit/call later
2610 functionMap[glslFunction->getName().c_str()] = function;
2611
2612 // Set the parameter id's
2613 for (int p = 0; p < (int)parameters.size(); ++p) {
2614 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2615 // give a name too
2616 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2617 }
2618 }
2619}
2620
2621// Process all the initializers, while skipping the functions and link objects
2622void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2623{
2624 builder.setBuildPoint(shaderEntry->getLastBlock());
2625 for (int i = 0; i < (int)initializers.size(); ++i) {
2626 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2627 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2628
2629 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002630 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002631 initializer->traverse(this);
2632 }
2633 }
2634}
2635
2636// Process all the functions, while skipping initializers.
2637void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2638{
2639 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2640 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002641 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002642 node->traverse(this);
2643 }
2644}
2645
2646void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2647{
qining25262b32016-05-06 17:25:16 -04002648 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002649 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002650 currentFunction = functionMap[node->getName().c_str()];
2651 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002652 builder.setBuildPoint(functionBlock);
2653}
2654
Rex Xu04db3f52015-09-16 11:44:02 +08002655void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002656{
Rex Xufc618912015-09-09 16:42:49 +08002657 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002658
2659 glslang::TSampler sampler = {};
2660 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002661 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002662 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2663 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2664 }
2665
John Kessenich140f3df2015-06-26 16:58:36 -06002666 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2667 builder.clearAccessChain();
2668 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002669
2670 // Special case l-value operands
2671 bool lvalue = false;
2672 switch (node.getOp()) {
2673 case glslang::EOpImageAtomicAdd:
2674 case glslang::EOpImageAtomicMin:
2675 case glslang::EOpImageAtomicMax:
2676 case glslang::EOpImageAtomicAnd:
2677 case glslang::EOpImageAtomicOr:
2678 case glslang::EOpImageAtomicXor:
2679 case glslang::EOpImageAtomicExchange:
2680 case glslang::EOpImageAtomicCompSwap:
2681 if (i == 0)
2682 lvalue = true;
2683 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002684 case glslang::EOpSparseImageLoad:
2685 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2686 lvalue = true;
2687 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002688 case glslang::EOpSparseTexture:
2689 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2690 lvalue = true;
2691 break;
2692 case glslang::EOpSparseTextureClamp:
2693 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2694 lvalue = true;
2695 break;
2696 case glslang::EOpSparseTextureLod:
2697 case glslang::EOpSparseTextureOffset:
2698 if (i == 3)
2699 lvalue = true;
2700 break;
2701 case glslang::EOpSparseTextureFetch:
2702 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2703 lvalue = true;
2704 break;
2705 case glslang::EOpSparseTextureFetchOffset:
2706 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2707 lvalue = true;
2708 break;
2709 case glslang::EOpSparseTextureLodOffset:
2710 case glslang::EOpSparseTextureGrad:
2711 case glslang::EOpSparseTextureOffsetClamp:
2712 if (i == 4)
2713 lvalue = true;
2714 break;
2715 case glslang::EOpSparseTextureGradOffset:
2716 case glslang::EOpSparseTextureGradClamp:
2717 if (i == 5)
2718 lvalue = true;
2719 break;
2720 case glslang::EOpSparseTextureGradOffsetClamp:
2721 if (i == 6)
2722 lvalue = true;
2723 break;
2724 case glslang::EOpSparseTextureGather:
2725 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2726 lvalue = true;
2727 break;
2728 case glslang::EOpSparseTextureGatherOffset:
2729 case glslang::EOpSparseTextureGatherOffsets:
2730 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2731 lvalue = true;
2732 break;
Rex Xufc618912015-09-09 16:42:49 +08002733 default:
2734 break;
2735 }
2736
Rex Xu6b86d492015-09-16 17:48:22 +08002737 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002738 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002739 else
John Kessenich32cfd492016-02-02 12:37:46 -07002740 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002741 }
2742}
2743
John Kessenichfc51d282015-08-19 13:34:18 -06002744void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002745{
John Kessenichfc51d282015-08-19 13:34:18 -06002746 builder.clearAccessChain();
2747 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002748 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002749}
John Kessenich140f3df2015-06-26 16:58:36 -06002750
John Kessenichfc51d282015-08-19 13:34:18 -06002751spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2752{
Rex Xufc618912015-09-09 16:42:49 +08002753 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002754 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002755 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002756 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002757
John Kessenichfc51d282015-08-19 13:34:18 -06002758 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002759 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2760 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2761 std::vector<spv::Id> arguments;
2762 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002763 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002764 else
2765 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002766 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002767
2768 spv::Builder::TextureParameters params = { };
2769 params.sampler = arguments[0];
2770
Rex Xu04db3f52015-09-16 11:44:02 +08002771 glslang::TCrackedTextureOp cracked;
2772 node->crackTexture(sampler, cracked);
2773
John Kessenichfc51d282015-08-19 13:34:18 -06002774 // Check for queries
2775 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002776 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2777 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002778 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002779
John Kessenichfc51d282015-08-19 13:34:18 -06002780 switch (node->getOp()) {
2781 case glslang::EOpImageQuerySize:
2782 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002783 if (arguments.size() > 1) {
2784 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002786 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002788 case glslang::EOpImageQuerySamples:
2789 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002791 case glslang::EOpTextureQueryLod:
2792 params.coords = arguments[1];
2793 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2794 case glslang::EOpTextureQueryLevels:
2795 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002796 case glslang::EOpSparseTexelsResident:
2797 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002798 default:
2799 assert(0);
2800 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002801 }
John Kessenich140f3df2015-06-26 16:58:36 -06002802 }
2803
Rex Xufc618912015-09-09 16:42:49 +08002804 // Check for image functions other than queries
2805 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002806 std::vector<spv::Id> operands;
2807 auto opIt = arguments.begin();
2808 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002809
2810 // Handle subpass operations
2811 // TODO: GLSL should change to have the "MS" only on the type rather than the
2812 // built-in function.
2813 if (cracked.subpass) {
2814 // add on the (0,0) coordinate
2815 spv::Id zero = builder.makeIntConstant(0);
2816 std::vector<spv::Id> comps;
2817 comps.push_back(zero);
2818 comps.push_back(zero);
2819 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2820 if (sampler.ms) {
2821 operands.push_back(spv::ImageOperandsSampleMask);
2822 operands.push_back(*(opIt++));
2823 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002824 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002825 }
2826
John Kessenich56bab042015-09-16 10:54:31 -06002827 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002828 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002829 if (sampler.ms) {
2830 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002831 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002832 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002833 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2834 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002835 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002836 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002837 if (sampler.ms) {
2838 operands.push_back(*(opIt + 1));
2839 operands.push_back(spv::ImageOperandsSampleMask);
2840 operands.push_back(*opIt);
2841 } else
2842 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002843 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002844 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2845 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002846 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002847 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2848 builder.addCapability(spv::CapabilitySparseResidency);
2849 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2850 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2851
2852 if (sampler.ms) {
2853 operands.push_back(spv::ImageOperandsSampleMask);
2854 operands.push_back(*opIt++);
2855 }
2856
2857 // Create the return type that was a special structure
2858 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002859 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002860 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2861 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2862
2863 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2864
2865 // Decode the return type
2866 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2867 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002868 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002869 // Process image atomic operations
2870
2871 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2872 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002873 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002874
John Kessenich8c8505c2016-07-26 12:50:38 -06002875 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002876 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002877
2878 std::vector<spv::Id> operands;
2879 operands.push_back(pointer);
2880 for (; opIt != arguments.end(); ++opIt)
2881 operands.push_back(*opIt);
2882
John Kessenich8c8505c2016-07-26 12:50:38 -06002883 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002884 }
2885 }
2886
2887 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002888 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002889 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2890
John Kessenichfc51d282015-08-19 13:34:18 -06002891 // check for bias argument
2892 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002893 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002894 int nonBiasArgCount = 2;
2895 if (cracked.offset)
2896 ++nonBiasArgCount;
2897 if (cracked.grad)
2898 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002899 if (cracked.lodClamp)
2900 ++nonBiasArgCount;
2901 if (sparse)
2902 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002903
2904 if ((int)arguments.size() > nonBiasArgCount)
2905 bias = true;
2906 }
2907
John Kessenicha5c33d62016-06-02 23:45:21 -06002908 // See if the sampler param should really be just the SPV image part
2909 if (cracked.fetch) {
2910 // a fetch needs to have the image extracted first
2911 if (builder.isSampledImage(params.sampler))
2912 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2913 }
2914
John Kessenichfc51d282015-08-19 13:34:18 -06002915 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002916
John Kessenichfc51d282015-08-19 13:34:18 -06002917 params.coords = arguments[1];
2918 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002919 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002920
2921 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002922 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002923 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002924 ++extraArgs;
2925 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002926 params.Dref = arguments[2];
2927 ++extraArgs;
2928 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002929 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002930 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002931 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002932 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002933 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002934 dRefComp = builder.getNumComponents(params.coords) - 1;
2935 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002936 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2937 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002938
2939 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002940 if (cracked.lod) {
2941 params.lod = arguments[2];
2942 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002943 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2944 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2945 noImplicitLod = true;
2946 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002947
2948 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002949 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002950 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002951 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002952 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002953
2954 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002955 if (cracked.grad) {
2956 params.gradX = arguments[2 + extraArgs];
2957 params.gradY = arguments[3 + extraArgs];
2958 extraArgs += 2;
2959 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002960
2961 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002962 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002963 params.offset = arguments[2 + extraArgs];
2964 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002965 } else if (cracked.offsets) {
2966 params.offsets = arguments[2 + extraArgs];
2967 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002968 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002969
2970 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002971 if (cracked.lodClamp) {
2972 params.lodClamp = arguments[2 + extraArgs];
2973 ++extraArgs;
2974 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002975
2976 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002977 if (sparse) {
2978 params.texelOut = arguments[2 + extraArgs];
2979 ++extraArgs;
2980 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002981
2982 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002983 if (bias) {
2984 params.bias = arguments[2 + extraArgs];
2985 ++extraArgs;
2986 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002987
2988 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002989 if (cracked.gather && ! sampler.shadow) {
2990 // default component is 0, if missing, otherwise an argument
2991 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002992 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002993 ++extraArgs;
2994 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002995 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002996 }
2997 }
John Kessenichfc51d282015-08-19 13:34:18 -06002998
John Kessenich65336482016-06-16 14:06:26 -06002999 // projective component (might not to move)
3000 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3001 // are divided by the last component of P."
3002 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3003 // unused components will appear after all used components."
3004 if (cracked.proj) {
3005 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3006 int projTargetComp;
3007 switch (sampler.dim) {
3008 case glslang::Esd1D: projTargetComp = 1; break;
3009 case glslang::Esd2D: projTargetComp = 2; break;
3010 case glslang::EsdRect: projTargetComp = 2; break;
3011 default: projTargetComp = projSourceComp; break;
3012 }
3013 // copy the projective coordinate if we have to
3014 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003015 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003016 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3017 projSourceComp);
3018 params.coords = builder.createCompositeInsert(projComp, params.coords,
3019 builder.getTypeId(params.coords), projTargetComp);
3020 }
3021 }
3022
John Kessenich8c8505c2016-07-26 12:50:38 -06003023 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003024}
3025
3026spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3027{
3028 // Grab the function's pointer from the previously created function
3029 spv::Function* function = functionMap[node->getName().c_str()];
3030 if (! function)
3031 return 0;
3032
3033 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3034 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3035
3036 // See comments in makeFunctions() for details about the semantics for parameter passing.
3037 //
3038 // These imply we need a four step process:
3039 // 1. Evaluate the arguments
3040 // 2. Allocate and make copies of in, out, and inout arguments
3041 // 3. Make the call
3042 // 4. Copy back the results
3043
3044 // 1. Evaluate the arguments
3045 std::vector<spv::Builder::AccessChain> lValues;
3046 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003047 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003049 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003050 // build l-value
3051 builder.clearAccessChain();
3052 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003053 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003054 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003055 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003056 // save l-value
3057 lValues.push_back(builder.getAccessChain());
3058 } else {
3059 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003060 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003061 }
3062 }
3063
3064 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3065 // copy the original into that space.
3066 //
3067 // Also, build up the list of actual arguments to pass in for the call
3068 int lValueCount = 0;
3069 int rValueCount = 0;
3070 std::vector<spv::Id> spvArgs;
3071 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003072 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003073 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003074 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003075 builder.setAccessChain(lValues[lValueCount]);
3076 arg = builder.accessChainGetLValue();
3077 ++lValueCount;
3078 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003079 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003080 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3081 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3082 // need to copy the input into output space
3083 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003084 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003085 builder.clearAccessChain();
3086 builder.setAccessChainLValue(arg);
3087 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003088 }
3089 ++lValueCount;
3090 } else {
3091 arg = rValues[rValueCount];
3092 ++rValueCount;
3093 }
3094 spvArgs.push_back(arg);
3095 }
3096
3097 // 3. Make the call.
3098 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003099 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003100
3101 // 4. Copy back out an "out" arguments.
3102 lValueCount = 0;
3103 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003104 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003105 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3106 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3107 spv::Id copy = builder.createLoad(spvArgs[a]);
3108 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003109 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003110 }
3111 ++lValueCount;
3112 }
3113 }
3114
3115 return result;
3116}
3117
3118// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003119spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3120 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003121 spv::Id typeId, spv::Id left, spv::Id right,
3122 glslang::TBasicType typeProxy, bool reduceComparison)
3123{
Rex Xu8ff43de2016-04-22 16:51:45 +08003124 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003125#ifdef AMD_EXTENSIONS
3126 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3127#else
John Kessenich140f3df2015-06-26 16:58:36 -06003128 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003129#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003130 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003131
3132 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003133 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003134 bool comparison = false;
3135
3136 switch (op) {
3137 case glslang::EOpAdd:
3138 case glslang::EOpAddAssign:
3139 if (isFloat)
3140 binOp = spv::OpFAdd;
3141 else
3142 binOp = spv::OpIAdd;
3143 break;
3144 case glslang::EOpSub:
3145 case glslang::EOpSubAssign:
3146 if (isFloat)
3147 binOp = spv::OpFSub;
3148 else
3149 binOp = spv::OpISub;
3150 break;
3151 case glslang::EOpMul:
3152 case glslang::EOpMulAssign:
3153 if (isFloat)
3154 binOp = spv::OpFMul;
3155 else
3156 binOp = spv::OpIMul;
3157 break;
3158 case glslang::EOpVectorTimesScalar:
3159 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003160 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003161 if (builder.isVector(right))
3162 std::swap(left, right);
3163 assert(builder.isScalar(right));
3164 needMatchingVectors = false;
3165 binOp = spv::OpVectorTimesScalar;
3166 } else
3167 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003168 break;
3169 case glslang::EOpVectorTimesMatrix:
3170 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003171 binOp = spv::OpVectorTimesMatrix;
3172 break;
3173 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003174 binOp = spv::OpMatrixTimesVector;
3175 break;
3176 case glslang::EOpMatrixTimesScalar:
3177 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003178 binOp = spv::OpMatrixTimesScalar;
3179 break;
3180 case glslang::EOpMatrixTimesMatrix:
3181 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003182 binOp = spv::OpMatrixTimesMatrix;
3183 break;
3184 case glslang::EOpOuterProduct:
3185 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003186 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 break;
3188
3189 case glslang::EOpDiv:
3190 case glslang::EOpDivAssign:
3191 if (isFloat)
3192 binOp = spv::OpFDiv;
3193 else if (isUnsigned)
3194 binOp = spv::OpUDiv;
3195 else
3196 binOp = spv::OpSDiv;
3197 break;
3198 case glslang::EOpMod:
3199 case glslang::EOpModAssign:
3200 if (isFloat)
3201 binOp = spv::OpFMod;
3202 else if (isUnsigned)
3203 binOp = spv::OpUMod;
3204 else
3205 binOp = spv::OpSMod;
3206 break;
3207 case glslang::EOpRightShift:
3208 case glslang::EOpRightShiftAssign:
3209 if (isUnsigned)
3210 binOp = spv::OpShiftRightLogical;
3211 else
3212 binOp = spv::OpShiftRightArithmetic;
3213 break;
3214 case glslang::EOpLeftShift:
3215 case glslang::EOpLeftShiftAssign:
3216 binOp = spv::OpShiftLeftLogical;
3217 break;
3218 case glslang::EOpAnd:
3219 case glslang::EOpAndAssign:
3220 binOp = spv::OpBitwiseAnd;
3221 break;
3222 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003223 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003224 binOp = spv::OpLogicalAnd;
3225 break;
3226 case glslang::EOpInclusiveOr:
3227 case glslang::EOpInclusiveOrAssign:
3228 binOp = spv::OpBitwiseOr;
3229 break;
3230 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003231 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 binOp = spv::OpLogicalOr;
3233 break;
3234 case glslang::EOpExclusiveOr:
3235 case glslang::EOpExclusiveOrAssign:
3236 binOp = spv::OpBitwiseXor;
3237 break;
3238 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003239 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003240 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242
3243 case glslang::EOpLessThan:
3244 case glslang::EOpGreaterThan:
3245 case glslang::EOpLessThanEqual:
3246 case glslang::EOpGreaterThanEqual:
3247 case glslang::EOpEqual:
3248 case glslang::EOpNotEqual:
3249 case glslang::EOpVectorEqual:
3250 case glslang::EOpVectorNotEqual:
3251 comparison = true;
3252 break;
3253 default:
3254 break;
3255 }
3256
John Kessenich7c1aa102015-10-15 13:29:11 -06003257 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003258 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003259 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003260 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003261 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003262
3263 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003264 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003265 builder.promoteScalar(precision, left, right);
3266
qining25262b32016-05-06 17:25:16 -04003267 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3268 addDecoration(result, noContraction);
3269 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003270 }
3271
3272 if (! comparison)
3273 return 0;
3274
John Kessenich7c1aa102015-10-15 13:29:11 -06003275 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003276
John Kessenich4583b612016-08-07 19:14:22 -06003277 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3278 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003279 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003280
3281 switch (op) {
3282 case glslang::EOpLessThan:
3283 if (isFloat)
3284 binOp = spv::OpFOrdLessThan;
3285 else if (isUnsigned)
3286 binOp = spv::OpULessThan;
3287 else
3288 binOp = spv::OpSLessThan;
3289 break;
3290 case glslang::EOpGreaterThan:
3291 if (isFloat)
3292 binOp = spv::OpFOrdGreaterThan;
3293 else if (isUnsigned)
3294 binOp = spv::OpUGreaterThan;
3295 else
3296 binOp = spv::OpSGreaterThan;
3297 break;
3298 case glslang::EOpLessThanEqual:
3299 if (isFloat)
3300 binOp = spv::OpFOrdLessThanEqual;
3301 else if (isUnsigned)
3302 binOp = spv::OpULessThanEqual;
3303 else
3304 binOp = spv::OpSLessThanEqual;
3305 break;
3306 case glslang::EOpGreaterThanEqual:
3307 if (isFloat)
3308 binOp = spv::OpFOrdGreaterThanEqual;
3309 else if (isUnsigned)
3310 binOp = spv::OpUGreaterThanEqual;
3311 else
3312 binOp = spv::OpSGreaterThanEqual;
3313 break;
3314 case glslang::EOpEqual:
3315 case glslang::EOpVectorEqual:
3316 if (isFloat)
3317 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003318 else if (isBool)
3319 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 else
3321 binOp = spv::OpIEqual;
3322 break;
3323 case glslang::EOpNotEqual:
3324 case glslang::EOpVectorNotEqual:
3325 if (isFloat)
3326 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003327 else if (isBool)
3328 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003329 else
3330 binOp = spv::OpINotEqual;
3331 break;
3332 default:
3333 break;
3334 }
3335
qining25262b32016-05-06 17:25:16 -04003336 if (binOp != spv::OpNop) {
3337 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3338 addDecoration(result, noContraction);
3339 return builder.setPrecision(result, precision);
3340 }
John Kessenich140f3df2015-06-26 16:58:36 -06003341
3342 return 0;
3343}
3344
John Kessenich04bb8a02015-12-12 12:28:14 -07003345//
3346// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3347// These can be any of:
3348//
3349// matrix * scalar
3350// scalar * matrix
3351// matrix * matrix linear algebraic
3352// matrix * vector
3353// vector * matrix
3354// matrix * matrix componentwise
3355// matrix op matrix op in {+, -, /}
3356// matrix op scalar op in {+, -, /}
3357// scalar op matrix op in {+, -, /}
3358//
qining25262b32016-05-06 17:25:16 -04003359spv::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 -07003360{
3361 bool firstClass = true;
3362
3363 // First, handle first-class matrix operations (* and matrix/scalar)
3364 switch (op) {
3365 case spv::OpFDiv:
3366 if (builder.isMatrix(left) && builder.isScalar(right)) {
3367 // turn matrix / scalar into a multiply...
3368 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3369 op = spv::OpMatrixTimesScalar;
3370 } else
3371 firstClass = false;
3372 break;
3373 case spv::OpMatrixTimesScalar:
3374 if (builder.isMatrix(right))
3375 std::swap(left, right);
3376 assert(builder.isScalar(right));
3377 break;
3378 case spv::OpVectorTimesMatrix:
3379 assert(builder.isVector(left));
3380 assert(builder.isMatrix(right));
3381 break;
3382 case spv::OpMatrixTimesVector:
3383 assert(builder.isMatrix(left));
3384 assert(builder.isVector(right));
3385 break;
3386 case spv::OpMatrixTimesMatrix:
3387 assert(builder.isMatrix(left));
3388 assert(builder.isMatrix(right));
3389 break;
3390 default:
3391 firstClass = false;
3392 break;
3393 }
3394
qining25262b32016-05-06 17:25:16 -04003395 if (firstClass) {
3396 spv::Id result = builder.createBinOp(op, typeId, left, right);
3397 addDecoration(result, noContraction);
3398 return builder.setPrecision(result, precision);
3399 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003400
LoopDawg592860c2016-06-09 08:57:35 -06003401 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003402 // The result type of all of them is the same type as the (a) matrix operand.
3403 // The algorithm is to:
3404 // - break the matrix(es) into vectors
3405 // - smear any scalar to a vector
3406 // - do vector operations
3407 // - make a matrix out the vector results
3408 switch (op) {
3409 case spv::OpFAdd:
3410 case spv::OpFSub:
3411 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003412 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003413 case spv::OpFMul:
3414 {
3415 // one time set up...
3416 bool leftMat = builder.isMatrix(left);
3417 bool rightMat = builder.isMatrix(right);
3418 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3419 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3420 spv::Id scalarType = builder.getScalarTypeId(typeId);
3421 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3422 std::vector<spv::Id> results;
3423 spv::Id smearVec = spv::NoResult;
3424 if (builder.isScalar(left))
3425 smearVec = builder.smearScalar(precision, left, vecType);
3426 else if (builder.isScalar(right))
3427 smearVec = builder.smearScalar(precision, right, vecType);
3428
3429 // do each vector op
3430 for (unsigned int c = 0; c < numCols; ++c) {
3431 std::vector<unsigned int> indexes;
3432 indexes.push_back(c);
3433 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3434 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003435 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3436 addDecoration(result, noContraction);
3437 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003438 }
3439
3440 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003441 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003442 }
3443 default:
3444 assert(0);
3445 return spv::NoResult;
3446 }
3447}
3448
qining25262b32016-05-06 17:25:16 -04003449spv::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 -06003450{
3451 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003452 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003453 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003454 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003455#ifdef AMD_EXTENSIONS
3456 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3457#else
Rex Xu04db3f52015-09-16 11:44:02 +08003458 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003459#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003460
3461 switch (op) {
3462 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003463 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003464 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003465 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003466 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003467 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003468 unaryOp = spv::OpSNegate;
3469 break;
3470
3471 case glslang::EOpLogicalNot:
3472 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 unaryOp = spv::OpLogicalNot;
3474 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003475 case glslang::EOpBitwiseNot:
3476 unaryOp = spv::OpNot;
3477 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003478
John Kessenich140f3df2015-06-26 16:58:36 -06003479 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003480 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003481 break;
3482 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003483 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003484 break;
3485 case glslang::EOpTranspose:
3486 unaryOp = spv::OpTranspose;
3487 break;
3488
3489 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003490 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003494 break;
3495 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003496 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003497 break;
3498 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003499 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003500 break;
3501 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003502 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 break;
3504 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003506 break;
3507 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003508 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003509 break;
3510 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 break;
3513
3514 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003515 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003516 break;
3517 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003518 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003519 break;
3520 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003521 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003522 break;
3523 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003524 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003525 break;
3526 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003527 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003528 break;
3529 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003530 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 break;
3532
3533 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003534 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003535 break;
3536 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003537 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003538 break;
3539
3540 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003541 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003542 break;
3543 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003544 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003545 break;
3546 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003547 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003548 break;
3549 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003550 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003551 break;
3552 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003553 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003554 break;
3555 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003556 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003557 break;
3558
3559 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003560 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
3562 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003563 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003564 break;
3565 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003566 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003567 break;
3568 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003569 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003570 break;
3571 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003572 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003573 break;
3574 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003575 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003576 break;
3577
3578 case glslang::EOpIsNan:
3579 unaryOp = spv::OpIsNan;
3580 break;
3581 case glslang::EOpIsInf:
3582 unaryOp = spv::OpIsInf;
3583 break;
LoopDawg592860c2016-06-09 08:57:35 -06003584 case glslang::EOpIsFinite:
3585 unaryOp = spv::OpIsFinite;
3586 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003587
Rex Xucbc426e2015-12-15 16:03:10 +08003588 case glslang::EOpFloatBitsToInt:
3589 case glslang::EOpFloatBitsToUint:
3590 case glslang::EOpIntBitsToFloat:
3591 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003592 case glslang::EOpDoubleBitsToInt64:
3593 case glslang::EOpDoubleBitsToUint64:
3594 case glslang::EOpInt64BitsToDouble:
3595 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003596 unaryOp = spv::OpBitcast;
3597 break;
3598
John Kessenich140f3df2015-06-26 16:58:36 -06003599 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003600 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003601 break;
3602 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003603 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003604 break;
3605 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003606 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003607 break;
3608 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003609 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003610 break;
3611 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003612 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003613 break;
3614 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003615 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003616 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003617 case glslang::EOpPackSnorm4x8:
3618 libCall = spv::GLSLstd450PackSnorm4x8;
3619 break;
3620 case glslang::EOpUnpackSnorm4x8:
3621 libCall = spv::GLSLstd450UnpackSnorm4x8;
3622 break;
3623 case glslang::EOpPackUnorm4x8:
3624 libCall = spv::GLSLstd450PackUnorm4x8;
3625 break;
3626 case glslang::EOpUnpackUnorm4x8:
3627 libCall = spv::GLSLstd450UnpackUnorm4x8;
3628 break;
3629 case glslang::EOpPackDouble2x32:
3630 libCall = spv::GLSLstd450PackDouble2x32;
3631 break;
3632 case glslang::EOpUnpackDouble2x32:
3633 libCall = spv::GLSLstd450UnpackDouble2x32;
3634 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003635
Rex Xu8ff43de2016-04-22 16:51:45 +08003636 case glslang::EOpPackInt2x32:
3637 case glslang::EOpUnpackInt2x32:
3638 case glslang::EOpPackUint2x32:
3639 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003640 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003641 break;
3642
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003643#ifdef AMD_EXTENSIONS
3644 case glslang::EOpPackFloat2x16:
3645 case glslang::EOpUnpackFloat2x16:
3646 unaryOp = spv::OpBitcast;
3647 break;
3648#endif
3649
John Kessenich140f3df2015-06-26 16:58:36 -06003650 case glslang::EOpDPdx:
3651 unaryOp = spv::OpDPdx;
3652 break;
3653 case glslang::EOpDPdy:
3654 unaryOp = spv::OpDPdy;
3655 break;
3656 case glslang::EOpFwidth:
3657 unaryOp = spv::OpFwidth;
3658 break;
3659 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003660 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003661 unaryOp = spv::OpDPdxFine;
3662 break;
3663 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003664 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003665 unaryOp = spv::OpDPdyFine;
3666 break;
3667 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003668 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003669 unaryOp = spv::OpFwidthFine;
3670 break;
3671 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003672 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003673 unaryOp = spv::OpDPdxCoarse;
3674 break;
3675 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003676 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003677 unaryOp = spv::OpDPdyCoarse;
3678 break;
3679 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003680 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003681 unaryOp = spv::OpFwidthCoarse;
3682 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003683 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003684 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003685 libCall = spv::GLSLstd450InterpolateAtCentroid;
3686 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 case glslang::EOpAny:
3688 unaryOp = spv::OpAny;
3689 break;
3690 case glslang::EOpAll:
3691 unaryOp = spv::OpAll;
3692 break;
3693
3694 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003695 if (isFloat)
3696 libCall = spv::GLSLstd450FAbs;
3697 else
3698 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003701 if (isFloat)
3702 libCall = spv::GLSLstd450FSign;
3703 else
3704 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003705 break;
3706
John Kessenichfc51d282015-08-19 13:34:18 -06003707 case glslang::EOpAtomicCounterIncrement:
3708 case glslang::EOpAtomicCounterDecrement:
3709 case glslang::EOpAtomicCounter:
3710 {
3711 // Handle all of the atomics in one place, in createAtomicOperation()
3712 std::vector<spv::Id> operands;
3713 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003714 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003715 }
3716
John Kessenichfc51d282015-08-19 13:34:18 -06003717 case glslang::EOpBitFieldReverse:
3718 unaryOp = spv::OpBitReverse;
3719 break;
3720 case glslang::EOpBitCount:
3721 unaryOp = spv::OpBitCount;
3722 break;
3723 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003724 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003725 break;
3726 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003727 if (isUnsigned)
3728 libCall = spv::GLSLstd450FindUMsb;
3729 else
3730 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003731 break;
3732
Rex Xu574ab042016-04-14 16:53:07 +08003733 case glslang::EOpBallot:
3734 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003735 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003736 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003737 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003738#ifdef AMD_EXTENSIONS
3739 case glslang::EOpMinInvocations:
3740 case glslang::EOpMaxInvocations:
3741 case glslang::EOpAddInvocations:
3742 case glslang::EOpMinInvocationsNonUniform:
3743 case glslang::EOpMaxInvocationsNonUniform:
3744 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003745 case glslang::EOpMinInvocationsInclusiveScan:
3746 case glslang::EOpMaxInvocationsInclusiveScan:
3747 case glslang::EOpAddInvocationsInclusiveScan:
3748 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3749 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3750 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3751 case glslang::EOpMinInvocationsExclusiveScan:
3752 case glslang::EOpMaxInvocationsExclusiveScan:
3753 case glslang::EOpAddInvocationsExclusiveScan:
3754 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3755 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3756 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003757#endif
Rex Xu51596642016-09-21 18:56:12 +08003758 {
3759 std::vector<spv::Id> operands;
3760 operands.push_back(operand);
3761 return createInvocationsOperation(op, typeId, operands, typeProxy);
3762 }
Rex Xu9d93a232016-05-05 12:30:44 +08003763
3764#ifdef AMD_EXTENSIONS
3765 case glslang::EOpMbcnt:
3766 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3767 libCall = spv::MbcntAMD;
3768 break;
3769
3770 case glslang::EOpCubeFaceIndex:
3771 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3772 libCall = spv::CubeFaceIndexAMD;
3773 break;
3774
3775 case glslang::EOpCubeFaceCoord:
3776 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3777 libCall = spv::CubeFaceCoordAMD;
3778 break;
3779#endif
Rex Xu338b1852016-05-05 20:38:33 +08003780
John Kessenich140f3df2015-06-26 16:58:36 -06003781 default:
3782 return 0;
3783 }
3784
3785 spv::Id id;
3786 if (libCall >= 0) {
3787 std::vector<spv::Id> args;
3788 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003789 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003790 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003791 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003792 }
John Kessenich140f3df2015-06-26 16:58:36 -06003793
qining25262b32016-05-06 17:25:16 -04003794 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003795 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003796}
3797
John Kessenich7a53f762016-01-20 11:19:27 -07003798// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003799spv::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 -07003800{
3801 // Handle unary operations vector by vector.
3802 // The result type is the same type as the original type.
3803 // The algorithm is to:
3804 // - break the matrix into vectors
3805 // - apply the operation to each vector
3806 // - make a matrix out the vector results
3807
3808 // get the types sorted out
3809 int numCols = builder.getNumColumns(operand);
3810 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003811 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3812 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003813 std::vector<spv::Id> results;
3814
3815 // do each vector op
3816 for (int c = 0; c < numCols; ++c) {
3817 std::vector<unsigned int> indexes;
3818 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003819 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3820 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3821 addDecoration(destVec, noContraction);
3822 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003823 }
3824
3825 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003826 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003827}
3828
Rex Xu73e3ce72016-04-27 18:48:17 +08003829spv::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 -06003830{
3831 spv::Op convOp = spv::OpNop;
3832 spv::Id zero = 0;
3833 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003834 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003835
3836 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3837
3838 switch (op) {
3839 case glslang::EOpConvIntToBool:
3840 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003841 case glslang::EOpConvInt64ToBool:
3842 case glslang::EOpConvUint64ToBool:
3843 zero = (op == glslang::EOpConvInt64ToBool ||
3844 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003845 zero = makeSmearedConstant(zero, vectorSize);
3846 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3847
3848 case glslang::EOpConvFloatToBool:
3849 zero = builder.makeFloatConstant(0.0F);
3850 zero = makeSmearedConstant(zero, vectorSize);
3851 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3852
3853 case glslang::EOpConvDoubleToBool:
3854 zero = builder.makeDoubleConstant(0.0);
3855 zero = makeSmearedConstant(zero, vectorSize);
3856 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3857
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003858#ifdef AMD_EXTENSIONS
3859 case glslang::EOpConvFloat16ToBool:
3860 zero = builder.makeFloat16Constant(0.0F);
3861 zero = makeSmearedConstant(zero, vectorSize);
3862 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3863#endif
3864
John Kessenich140f3df2015-06-26 16:58:36 -06003865 case glslang::EOpConvBoolToFloat:
3866 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003867 zero = builder.makeFloatConstant(0.0F);
3868 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003869 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003870
John Kessenich140f3df2015-06-26 16:58:36 -06003871 case glslang::EOpConvBoolToDouble:
3872 convOp = spv::OpSelect;
3873 zero = builder.makeDoubleConstant(0.0);
3874 one = builder.makeDoubleConstant(1.0);
3875 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003876
3877#ifdef AMD_EXTENSIONS
3878 case glslang::EOpConvBoolToFloat16:
3879 convOp = spv::OpSelect;
3880 zero = builder.makeFloat16Constant(0.0F);
3881 one = builder.makeFloat16Constant(1.0F);
3882 break;
3883#endif
3884
John Kessenich140f3df2015-06-26 16:58:36 -06003885 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003886 case glslang::EOpConvBoolToInt64:
3887 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3888 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003889 convOp = spv::OpSelect;
3890 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003891
John Kessenich140f3df2015-06-26 16:58:36 -06003892 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003893 case glslang::EOpConvBoolToUint64:
3894 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3895 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 convOp = spv::OpSelect;
3897 break;
3898
3899 case glslang::EOpConvIntToFloat:
3900 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003901 case glslang::EOpConvInt64ToFloat:
3902 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003903#ifdef AMD_EXTENSIONS
3904 case glslang::EOpConvIntToFloat16:
3905 case glslang::EOpConvInt64ToFloat16:
3906#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003907 convOp = spv::OpConvertSToF;
3908 break;
3909
3910 case glslang::EOpConvUintToFloat:
3911 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003912 case glslang::EOpConvUint64ToFloat:
3913 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003914#ifdef AMD_EXTENSIONS
3915 case glslang::EOpConvUintToFloat16:
3916 case glslang::EOpConvUint64ToFloat16:
3917#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003918 convOp = spv::OpConvertUToF;
3919 break;
3920
3921 case glslang::EOpConvDoubleToFloat:
3922 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003923#ifdef AMD_EXTENSIONS
3924 case glslang::EOpConvDoubleToFloat16:
3925 case glslang::EOpConvFloat16ToDouble:
3926 case glslang::EOpConvFloatToFloat16:
3927 case glslang::EOpConvFloat16ToFloat:
3928#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003929 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003930 if (builder.isMatrixType(destType))
3931 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003932 break;
3933
3934 case glslang::EOpConvFloatToInt:
3935 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003936 case glslang::EOpConvFloatToInt64:
3937 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003938#ifdef AMD_EXTENSIONS
3939 case glslang::EOpConvFloat16ToInt:
3940 case glslang::EOpConvFloat16ToInt64:
3941#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003942 convOp = spv::OpConvertFToS;
3943 break;
3944
3945 case glslang::EOpConvUintToInt:
3946 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003947 case glslang::EOpConvUint64ToInt64:
3948 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003949 if (builder.isInSpecConstCodeGenMode()) {
3950 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003951 zero = (op == glslang::EOpConvUint64ToInt64 ||
3952 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003953 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003954 // Use OpIAdd, instead of OpBitcast to do the conversion when
3955 // generating for OpSpecConstantOp instruction.
3956 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3957 }
3958 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003959 convOp = spv::OpBitcast;
3960 break;
3961
3962 case glslang::EOpConvFloatToUint:
3963 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003964 case glslang::EOpConvFloatToUint64:
3965 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003966#ifdef AMD_EXTENSIONS
3967 case glslang::EOpConvFloat16ToUint:
3968 case glslang::EOpConvFloat16ToUint64:
3969#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003970 convOp = spv::OpConvertFToU;
3971 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003972
3973 case glslang::EOpConvIntToInt64:
3974 case glslang::EOpConvInt64ToInt:
3975 convOp = spv::OpSConvert;
3976 break;
3977
3978 case glslang::EOpConvUintToUint64:
3979 case glslang::EOpConvUint64ToUint:
3980 convOp = spv::OpUConvert;
3981 break;
3982
3983 case glslang::EOpConvIntToUint64:
3984 case glslang::EOpConvInt64ToUint:
3985 case glslang::EOpConvUint64ToInt:
3986 case glslang::EOpConvUintToInt64:
3987 // OpSConvert/OpUConvert + OpBitCast
3988 switch (op) {
3989 case glslang::EOpConvIntToUint64:
3990 convOp = spv::OpSConvert;
3991 type = builder.makeIntType(64);
3992 break;
3993 case glslang::EOpConvInt64ToUint:
3994 convOp = spv::OpSConvert;
3995 type = builder.makeIntType(32);
3996 break;
3997 case glslang::EOpConvUint64ToInt:
3998 convOp = spv::OpUConvert;
3999 type = builder.makeUintType(32);
4000 break;
4001 case glslang::EOpConvUintToInt64:
4002 convOp = spv::OpUConvert;
4003 type = builder.makeUintType(64);
4004 break;
4005 default:
4006 assert(0);
4007 break;
4008 }
4009
4010 if (vectorSize > 0)
4011 type = builder.makeVectorType(type, vectorSize);
4012
4013 operand = builder.createUnaryOp(convOp, type, operand);
4014
4015 if (builder.isInSpecConstCodeGenMode()) {
4016 // Build zero scalar or vector for OpIAdd.
4017 zero = (op == glslang::EOpConvIntToUint64 ||
4018 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4019 zero = makeSmearedConstant(zero, vectorSize);
4020 // Use OpIAdd, instead of OpBitcast to do the conversion when
4021 // generating for OpSpecConstantOp instruction.
4022 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4023 }
4024 // For normal run-time conversion instruction, use OpBitcast.
4025 convOp = spv::OpBitcast;
4026 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004027 default:
4028 break;
4029 }
4030
4031 spv::Id result = 0;
4032 if (convOp == spv::OpNop)
4033 return result;
4034
4035 if (convOp == spv::OpSelect) {
4036 zero = makeSmearedConstant(zero, vectorSize);
4037 one = makeSmearedConstant(one, vectorSize);
4038 result = builder.createTriOp(convOp, destType, operand, one, zero);
4039 } else
4040 result = builder.createUnaryOp(convOp, destType, operand);
4041
John Kessenich32cfd492016-02-02 12:37:46 -07004042 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004043}
4044
4045spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4046{
4047 if (vectorSize == 0)
4048 return constant;
4049
4050 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4051 std::vector<spv::Id> components;
4052 for (int c = 0; c < vectorSize; ++c)
4053 components.push_back(constant);
4054 return builder.makeCompositeConstant(vectorTypeId, components);
4055}
4056
John Kessenich426394d2015-07-23 10:22:48 -06004057// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004058spv::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 -06004059{
4060 spv::Op opCode = spv::OpNop;
4061
4062 switch (op) {
4063 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004064 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004065 opCode = spv::OpAtomicIAdd;
4066 break;
4067 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004068 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004069 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004070 break;
4071 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004072 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004073 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004074 break;
4075 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004076 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004077 opCode = spv::OpAtomicAnd;
4078 break;
4079 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004080 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004081 opCode = spv::OpAtomicOr;
4082 break;
4083 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004084 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004085 opCode = spv::OpAtomicXor;
4086 break;
4087 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004088 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004089 opCode = spv::OpAtomicExchange;
4090 break;
4091 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004092 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004093 opCode = spv::OpAtomicCompareExchange;
4094 break;
4095 case glslang::EOpAtomicCounterIncrement:
4096 opCode = spv::OpAtomicIIncrement;
4097 break;
4098 case glslang::EOpAtomicCounterDecrement:
4099 opCode = spv::OpAtomicIDecrement;
4100 break;
4101 case glslang::EOpAtomicCounter:
4102 opCode = spv::OpAtomicLoad;
4103 break;
4104 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004105 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004106 break;
4107 }
4108
4109 // Sort out the operands
4110 // - mapping from glslang -> SPV
4111 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004112 // - compare-exchange swaps the value and comparator
4113 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004114 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4115 auto opIt = operands.begin(); // walk the glslang operands
4116 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004117 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4118 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4119 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004120 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4121 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004122 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004123 spvAtomicOperands.push_back(*(opIt + 1));
4124 spvAtomicOperands.push_back(*opIt);
4125 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004126 }
John Kessenich426394d2015-07-23 10:22:48 -06004127
John Kessenich3e60a6f2015-09-14 22:45:16 -06004128 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004129 for (; opIt != operands.end(); ++opIt)
4130 spvAtomicOperands.push_back(*opIt);
4131
4132 return builder.createOp(opCode, typeId, spvAtomicOperands);
4133}
4134
John Kessenich91cef522016-05-05 16:45:40 -06004135// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004136spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004137{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004138#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004139 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004140 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004141#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004142
Rex Xu51596642016-09-21 18:56:12 +08004143 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004144 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004145 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4146
chaocf200da82016-12-20 12:44:35 -08004147 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4148 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004149 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4150 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4151 } else {
4152 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004153#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004154 if (op == glslang::EOpMinInvocationsNonUniform ||
4155 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004156 op == glslang::EOpAddInvocationsNonUniform ||
4157 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4158 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4159 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4160 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4161 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4162 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004163 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004164#endif
Rex Xu51596642016-09-21 18:56:12 +08004165
4166 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004167#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004168 switch (op) {
4169 case glslang::EOpMinInvocations:
4170 case glslang::EOpMaxInvocations:
4171 case glslang::EOpAddInvocations:
4172 case glslang::EOpMinInvocationsNonUniform:
4173 case glslang::EOpMaxInvocationsNonUniform:
4174 case glslang::EOpAddInvocationsNonUniform:
4175 groupOperation = spv::GroupOperationReduce;
4176 spvGroupOperands.push_back(groupOperation);
4177 break;
4178 case glslang::EOpMinInvocationsInclusiveScan:
4179 case glslang::EOpMaxInvocationsInclusiveScan:
4180 case glslang::EOpAddInvocationsInclusiveScan:
4181 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4182 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4183 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4184 groupOperation = spv::GroupOperationInclusiveScan;
4185 spvGroupOperands.push_back(groupOperation);
4186 break;
4187 case glslang::EOpMinInvocationsExclusiveScan:
4188 case glslang::EOpMaxInvocationsExclusiveScan:
4189 case glslang::EOpAddInvocationsExclusiveScan:
4190 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4191 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4192 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4193 groupOperation = spv::GroupOperationExclusiveScan;
4194 spvGroupOperands.push_back(groupOperation);
4195 break;
4196 }
Rex Xu9d93a232016-05-05 12:30:44 +08004197#endif
Rex Xu51596642016-09-21 18:56:12 +08004198 }
4199
4200 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4201 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004202
4203 switch (op) {
4204 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004205 opCode = spv::OpGroupAny;
4206 break;
John Kessenich91cef522016-05-05 16:45:40 -06004207 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004208 opCode = spv::OpGroupAll;
4209 break;
John Kessenich91cef522016-05-05 16:45:40 -06004210 case glslang::EOpAllInvocationsEqual:
4211 {
Rex Xu51596642016-09-21 18:56:12 +08004212 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4213 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004214
4215 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4216 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4217 }
Rex Xu51596642016-09-21 18:56:12 +08004218
4219 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004220 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004221 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004222 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004223 break;
4224 case glslang::EOpReadFirstInvocation:
4225 opCode = spv::OpSubgroupFirstInvocationKHR;
4226 break;
4227 case glslang::EOpBallot:
4228 {
4229 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4230 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4231 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4232 //
4233 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4234 //
4235 spv::Id uintType = builder.makeUintType(32);
4236 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4237 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4238
4239 std::vector<spv::Id> components;
4240 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4241 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4242
4243 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4244 return builder.createUnaryOp(spv::OpBitcast, typeId,
4245 builder.createCompositeConstruct(uvec2Type, components));
4246 }
4247
Rex Xu9d93a232016-05-05 12:30:44 +08004248#ifdef AMD_EXTENSIONS
4249 case glslang::EOpMinInvocations:
4250 case glslang::EOpMaxInvocations:
4251 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004252 case glslang::EOpMinInvocationsInclusiveScan:
4253 case glslang::EOpMaxInvocationsInclusiveScan:
4254 case glslang::EOpAddInvocationsInclusiveScan:
4255 case glslang::EOpMinInvocationsExclusiveScan:
4256 case glslang::EOpMaxInvocationsExclusiveScan:
4257 case glslang::EOpAddInvocationsExclusiveScan:
4258 if (op == glslang::EOpMinInvocations ||
4259 op == glslang::EOpMinInvocationsInclusiveScan ||
4260 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004261 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004262 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004263 else {
4264 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004265 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004266 else
Rex Xu51596642016-09-21 18:56:12 +08004267 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004268 }
Rex Xu430ef402016-10-14 17:22:23 +08004269 } else if (op == glslang::EOpMaxInvocations ||
4270 op == glslang::EOpMaxInvocationsInclusiveScan ||
4271 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004272 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004273 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004274 else {
4275 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004276 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004277 else
Rex Xu51596642016-09-21 18:56:12 +08004278 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004279 }
4280 } else {
4281 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004282 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004283 else
Rex Xu51596642016-09-21 18:56:12 +08004284 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004285 }
4286
Rex Xu2bbbe062016-08-23 15:41:05 +08004287 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004288 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004289
4290 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004291 case glslang::EOpMinInvocationsNonUniform:
4292 case glslang::EOpMaxInvocationsNonUniform:
4293 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004294 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4295 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4296 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4297 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4298 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4299 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4300 if (op == glslang::EOpMinInvocationsNonUniform ||
4301 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4302 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004303 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004304 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004305 else {
4306 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004307 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004308 else
Rex Xu51596642016-09-21 18:56:12 +08004309 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004310 }
4311 }
Rex Xu430ef402016-10-14 17:22:23 +08004312 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4313 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4314 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004315 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004316 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004317 else {
4318 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004319 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004320 else
Rex Xu51596642016-09-21 18:56:12 +08004321 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004322 }
4323 }
4324 else {
4325 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004326 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004327 else
Rex Xu51596642016-09-21 18:56:12 +08004328 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004329 }
4330
Rex Xu2bbbe062016-08-23 15:41:05 +08004331 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004332 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004333
4334 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004335#endif
John Kessenich91cef522016-05-05 16:45:40 -06004336 default:
4337 logger->missingFunctionality("invocation operation");
4338 return spv::NoResult;
4339 }
Rex Xu51596642016-09-21 18:56:12 +08004340
4341 assert(opCode != spv::OpNop);
4342 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004343}
4344
Rex Xu2bbbe062016-08-23 15:41:05 +08004345// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004346spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004347{
Rex Xub7072052016-09-26 15:53:40 +08004348#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004349 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4350 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004351 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004352 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004353 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4354 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4355 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004356#else
4357 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4358 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004359 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4360 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004361#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004362
4363 // Handle group invocation operations scalar by scalar.
4364 // The result type is the same type as the original type.
4365 // The algorithm is to:
4366 // - break the vector into scalars
4367 // - apply the operation to each scalar
4368 // - make a vector out the scalar results
4369
4370 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004371 int numComponents = builder.getNumComponents(operands[0]);
4372 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004373 std::vector<spv::Id> results;
4374
4375 // do each scalar op
4376 for (int comp = 0; comp < numComponents; ++comp) {
4377 std::vector<unsigned int> indexes;
4378 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004379 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004380 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004381 if (op == spv::OpSubgroupReadInvocationKHR) {
4382 spvGroupOperands.push_back(scalar);
4383 spvGroupOperands.push_back(operands[1]);
4384 } else if (op == spv::OpGroupBroadcast) {
4385 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004386 spvGroupOperands.push_back(scalar);
4387 spvGroupOperands.push_back(operands[1]);
4388 } else {
chaocf200da82016-12-20 12:44:35 -08004389 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004390 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004391 spvGroupOperands.push_back(scalar);
4392 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004393
Rex Xub7072052016-09-26 15:53:40 +08004394 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004395 }
4396
4397 // put the pieces together
4398 return builder.createCompositeConstruct(typeId, results);
4399}
Rex Xu2bbbe062016-08-23 15:41:05 +08004400
John Kessenich5e4b1242015-08-06 22:53:06 -06004401spv::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 -06004402{
Rex Xu8ff43de2016-04-22 16:51:45 +08004403 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004404#ifdef AMD_EXTENSIONS
4405 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4406#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004407 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004408#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004409
John Kessenich140f3df2015-06-26 16:58:36 -06004410 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004411 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004412 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004413 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004414 spv::Id typeId0 = 0;
4415 if (consumedOperands > 0)
4416 typeId0 = builder.getTypeId(operands[0]);
4417 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004418
4419 switch (op) {
4420 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 if (isFloat)
4422 libCall = spv::GLSLstd450FMin;
4423 else if (isUnsigned)
4424 libCall = spv::GLSLstd450UMin;
4425 else
4426 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004427 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004428 break;
4429 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004430 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004431 break;
4432 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004433 if (isFloat)
4434 libCall = spv::GLSLstd450FMax;
4435 else if (isUnsigned)
4436 libCall = spv::GLSLstd450UMax;
4437 else
4438 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004439 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004440 break;
4441 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004442 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004443 break;
4444 case glslang::EOpDot:
4445 opCode = spv::OpDot;
4446 break;
4447 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004448 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004449 break;
4450
4451 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004452 if (isFloat)
4453 libCall = spv::GLSLstd450FClamp;
4454 else if (isUnsigned)
4455 libCall = spv::GLSLstd450UClamp;
4456 else
4457 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004458 builder.promoteScalar(precision, operands.front(), operands[1]);
4459 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004460 break;
4461 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004462 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4463 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004464 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004465 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004466 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004467 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004468 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004469 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004470 break;
4471 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004472 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004473 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004474 break;
4475 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004476 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004477 builder.promoteScalar(precision, operands[0], operands[2]);
4478 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004479 break;
4480
4481 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004482 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004483 break;
4484 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004485 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004486 break;
4487 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004488 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004489 break;
4490 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004491 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004492 break;
4493 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004496 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004497 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004498 libCall = spv::GLSLstd450InterpolateAtSample;
4499 break;
4500 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004501 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004502 libCall = spv::GLSLstd450InterpolateAtOffset;
4503 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004504 case glslang::EOpAddCarry:
4505 opCode = spv::OpIAddCarry;
4506 typeId = builder.makeStructResultType(typeId0, typeId0);
4507 consumedOperands = 2;
4508 break;
4509 case glslang::EOpSubBorrow:
4510 opCode = spv::OpISubBorrow;
4511 typeId = builder.makeStructResultType(typeId0, typeId0);
4512 consumedOperands = 2;
4513 break;
4514 case glslang::EOpUMulExtended:
4515 opCode = spv::OpUMulExtended;
4516 typeId = builder.makeStructResultType(typeId0, typeId0);
4517 consumedOperands = 2;
4518 break;
4519 case glslang::EOpIMulExtended:
4520 opCode = spv::OpSMulExtended;
4521 typeId = builder.makeStructResultType(typeId0, typeId0);
4522 consumedOperands = 2;
4523 break;
4524 case glslang::EOpBitfieldExtract:
4525 if (isUnsigned)
4526 opCode = spv::OpBitFieldUExtract;
4527 else
4528 opCode = spv::OpBitFieldSExtract;
4529 break;
4530 case glslang::EOpBitfieldInsert:
4531 opCode = spv::OpBitFieldInsert;
4532 break;
4533
4534 case glslang::EOpFma:
4535 libCall = spv::GLSLstd450Fma;
4536 break;
4537 case glslang::EOpFrexp:
4538 libCall = spv::GLSLstd450FrexpStruct;
4539 if (builder.getNumComponents(operands[0]) == 1)
4540 frexpIntType = builder.makeIntegerType(32, true);
4541 else
4542 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4543 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4544 consumedOperands = 1;
4545 break;
4546 case glslang::EOpLdexp:
4547 libCall = spv::GLSLstd450Ldexp;
4548 break;
4549
Rex Xu574ab042016-04-14 16:53:07 +08004550 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004551 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004552
Rex Xu9d93a232016-05-05 12:30:44 +08004553#ifdef AMD_EXTENSIONS
4554 case glslang::EOpSwizzleInvocations:
4555 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4556 libCall = spv::SwizzleInvocationsAMD;
4557 break;
4558 case glslang::EOpSwizzleInvocationsMasked:
4559 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4560 libCall = spv::SwizzleInvocationsMaskedAMD;
4561 break;
4562 case glslang::EOpWriteInvocation:
4563 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4564 libCall = spv::WriteInvocationAMD;
4565 break;
4566
4567 case glslang::EOpMin3:
4568 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4569 if (isFloat)
4570 libCall = spv::FMin3AMD;
4571 else {
4572 if (isUnsigned)
4573 libCall = spv::UMin3AMD;
4574 else
4575 libCall = spv::SMin3AMD;
4576 }
4577 break;
4578 case glslang::EOpMax3:
4579 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4580 if (isFloat)
4581 libCall = spv::FMax3AMD;
4582 else {
4583 if (isUnsigned)
4584 libCall = spv::UMax3AMD;
4585 else
4586 libCall = spv::SMax3AMD;
4587 }
4588 break;
4589 case glslang::EOpMid3:
4590 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4591 if (isFloat)
4592 libCall = spv::FMid3AMD;
4593 else {
4594 if (isUnsigned)
4595 libCall = spv::UMid3AMD;
4596 else
4597 libCall = spv::SMid3AMD;
4598 }
4599 break;
4600
4601 case glslang::EOpInterpolateAtVertex:
4602 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4603 libCall = spv::InterpolateAtVertexAMD;
4604 break;
4605#endif
4606
John Kessenich140f3df2015-06-26 16:58:36 -06004607 default:
4608 return 0;
4609 }
4610
4611 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004612 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004613 // Use an extended instruction from the standard library.
4614 // Construct the call arguments, without modifying the original operands vector.
4615 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4616 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004617 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004618 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004619 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004620 case 0:
4621 // should all be handled by visitAggregate and createNoArgOperation
4622 assert(0);
4623 return 0;
4624 case 1:
4625 // should all be handled by createUnaryOperation
4626 assert(0);
4627 return 0;
4628 case 2:
4629 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4630 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004631 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004632 // anything 3 or over doesn't have l-value operands, so all should be consumed
4633 assert(consumedOperands == operands.size());
4634 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004635 break;
4636 }
4637 }
4638
John Kessenich55e7d112015-11-15 21:33:39 -07004639 // Decode the return types that were structures
4640 switch (op) {
4641 case glslang::EOpAddCarry:
4642 case glslang::EOpSubBorrow:
4643 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4644 id = builder.createCompositeExtract(id, typeId0, 0);
4645 break;
4646 case glslang::EOpUMulExtended:
4647 case glslang::EOpIMulExtended:
4648 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4649 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4650 break;
4651 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004652 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004653 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4654 id = builder.createCompositeExtract(id, typeId0, 0);
4655 break;
4656 default:
4657 break;
4658 }
4659
John Kessenich32cfd492016-02-02 12:37:46 -07004660 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004661}
4662
Rex Xu9d93a232016-05-05 12:30:44 +08004663// Intrinsics with no arguments (or no return value, and no precision).
4664spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004665{
4666 // TODO: get the barrier operands correct
4667
4668 switch (op) {
4669 case glslang::EOpEmitVertex:
4670 builder.createNoResultOp(spv::OpEmitVertex);
4671 return 0;
4672 case glslang::EOpEndPrimitive:
4673 builder.createNoResultOp(spv::OpEndPrimitive);
4674 return 0;
4675 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004676 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004677 return 0;
4678 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004679 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004680 return 0;
4681 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004682 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004683 return 0;
4684 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004685 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004686 return 0;
4687 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004688 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004689 return 0;
4690 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004691 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004692 return 0;
4693 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004694 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004695 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004696 case glslang::EOpAllMemoryBarrierWithGroupSync:
4697 // Control barrier with non-"None" semantic is also a memory barrier.
4698 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4699 return 0;
4700 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4701 // Control barrier with non-"None" semantic is also a memory barrier.
4702 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4703 return 0;
4704 case glslang::EOpWorkgroupMemoryBarrier:
4705 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4706 return 0;
4707 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4708 // Control barrier with non-"None" semantic is also a memory barrier.
4709 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4710 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004711#ifdef AMD_EXTENSIONS
4712 case glslang::EOpTime:
4713 {
4714 std::vector<spv::Id> args; // Dummy arguments
4715 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4716 return builder.setPrecision(id, precision);
4717 }
4718#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004719 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004720 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004721 return 0;
4722 }
4723}
4724
4725spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4726{
John Kessenich2f273362015-07-18 22:34:27 -06004727 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004728 spv::Id id;
4729 if (symbolValues.end() != iter) {
4730 id = iter->second;
4731 return id;
4732 }
4733
4734 // it was not found, create it
4735 id = createSpvVariable(symbol);
4736 symbolValues[symbol->getId()] = id;
4737
Rex Xuc884b4a2016-06-29 15:03:44 +08004738 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004739 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004740 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004741 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004742 if (symbol->getType().getQualifier().hasSpecConstantId())
4743 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004744 if (symbol->getQualifier().hasIndex())
4745 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4746 if (symbol->getQualifier().hasComponent())
4747 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4748 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004749 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004750 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004751 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004752 if (symbol->getQualifier().hasXfbBuffer())
4753 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4754 if (symbol->getQualifier().hasXfbOffset())
4755 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4756 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004757 // atomic counters use this:
4758 if (symbol->getQualifier().hasOffset())
4759 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004760 }
4761
scygan2c864272016-05-18 18:09:17 +02004762 if (symbol->getQualifier().hasLocation())
4763 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004764 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004765 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004766 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004767 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004768 }
John Kessenich140f3df2015-06-26 16:58:36 -06004769 if (symbol->getQualifier().hasSet())
4770 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004771 else if (IsDescriptorResource(symbol->getType())) {
4772 // default to 0
4773 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4774 }
John Kessenich140f3df2015-06-26 16:58:36 -06004775 if (symbol->getQualifier().hasBinding())
4776 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004777 if (symbol->getQualifier().hasAttachment())
4778 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004779 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004780 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004781 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004782 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004783 if (symbol->getQualifier().hasXfbBuffer())
4784 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4785 }
4786
Rex Xu1da878f2016-02-21 20:59:01 +08004787 if (symbol->getType().isImage()) {
4788 std::vector<spv::Decoration> memory;
4789 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4790 for (unsigned int i = 0; i < memory.size(); ++i)
4791 addDecoration(id, memory[i]);
4792 }
4793
John Kessenich140f3df2015-06-26 16:58:36 -06004794 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004795 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004796 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004797 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004798
John Kessenichecba76f2017-01-06 00:34:48 -07004799#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004800 if (builtIn == spv::BuiltInSampleMask) {
4801 spv::Decoration decoration;
4802 // GL_NV_sample_mask_override_coverage extension
4803 if (glslangIntermediate->getLayoutOverrideCoverage())
4804 decoration = (spv::Decoration)spv::OverrideCoverageNV;
4805 else
4806 decoration = (spv::Decoration)spv::DecorationMax;
4807 addDecoration(id, decoration);
4808 if (decoration != spv::DecorationMax) {
4809 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4810 }
4811 }
chaoc6e5acae2016-12-20 13:28:52 -08004812 if (symbol->getQualifier().layoutPassthrough) {
4813 addDecoration(id, spv::PassthroughNV);
4814 builder.addCapability(spv::GeometryShaderPassthroughNV);
4815 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4816 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004817#endif
4818
John Kessenich140f3df2015-06-26 16:58:36 -06004819 return id;
4820}
4821
John Kessenich55e7d112015-11-15 21:33:39 -07004822// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004823void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4824{
John Kessenich4016e382016-07-15 11:53:56 -06004825 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004826 builder.addDecoration(id, dec);
4827}
4828
John Kessenich55e7d112015-11-15 21:33:39 -07004829// If 'dec' is valid, add a one-operand decoration to an object
4830void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4831{
John Kessenich4016e382016-07-15 11:53:56 -06004832 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004833 builder.addDecoration(id, dec, value);
4834}
4835
4836// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004837void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4838{
John Kessenich4016e382016-07-15 11:53:56 -06004839 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004840 builder.addMemberDecoration(id, (unsigned)member, dec);
4841}
4842
John Kessenich92187592016-02-01 13:45:25 -07004843// If 'dec' is valid, add a one-operand decoration to a struct member
4844void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4845{
John Kessenich4016e382016-07-15 11:53:56 -06004846 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004847 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4848}
4849
John Kessenich55e7d112015-11-15 21:33:39 -07004850// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004851// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004852//
4853// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4854//
4855// Recursively walk the nodes. The nodes form a tree whose leaves are
4856// regular constants, which themselves are trees that createSpvConstant()
4857// recursively walks. So, this function walks the "top" of the tree:
4858// - emit specialization constant-building instructions for specConstant
4859// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004860spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004861{
John Kessenich7cc0e282016-03-20 00:46:02 -06004862 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004863
qining4f4bb812016-04-03 23:55:17 -04004864 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004865 if (! node.getQualifier().specConstant) {
4866 // hand off to the non-spec-constant path
4867 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4868 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004869 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004870 nextConst, false);
4871 }
4872
4873 // We now know we have a specialization constant to build
4874
John Kessenichd94c0032016-05-30 19:29:40 -06004875 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004876 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4877 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4878 std::vector<spv::Id> dimConstId;
4879 for (int dim = 0; dim < 3; ++dim) {
4880 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4881 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4882 if (specConst)
4883 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4884 }
4885 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4886 }
4887
4888 // An AST node labelled as specialization constant should be a symbol node.
4889 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4890 if (auto* sn = node.getAsSymbolNode()) {
4891 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004892 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4893 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4894 // will set the builder into spec constant op instruction generating mode.
4895 sub_tree->traverse(this);
4896 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004897 } else if (auto* const_union_array = &sn->getConstArray()){
4898 int nextConst = 0;
4899 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004900 }
4901 }
qining4f4bb812016-04-03 23:55:17 -04004902
4903 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4904 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004905 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004906 exit(1);
4907 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004908}
4909
John Kessenich140f3df2015-06-26 16:58:36 -06004910// Use 'consts' as the flattened glslang source of scalar constants to recursively
4911// build the aggregate SPIR-V constant.
4912//
4913// If there are not enough elements present in 'consts', 0 will be substituted;
4914// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4915//
qining08408382016-03-21 09:51:37 -04004916spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004917{
4918 // vector of constants for SPIR-V
4919 std::vector<spv::Id> spvConsts;
4920
4921 // Type is used for struct and array constants
4922 spv::Id typeId = convertGlslangToSpvType(glslangType);
4923
4924 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004925 glslang::TType elementType(glslangType, 0);
4926 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004927 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004928 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004929 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004930 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004931 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004932 } else if (glslangType.getStruct()) {
4933 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4934 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004935 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004936 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004937 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4938 bool zero = nextConst >= consts.size();
4939 switch (glslangType.getBasicType()) {
4940 case glslang::EbtInt:
4941 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4942 break;
4943 case glslang::EbtUint:
4944 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4945 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004946 case glslang::EbtInt64:
4947 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4948 break;
4949 case glslang::EbtUint64:
4950 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4951 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004952 case glslang::EbtFloat:
4953 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4954 break;
4955 case glslang::EbtDouble:
4956 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4957 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004958#ifdef AMD_EXTENSIONS
4959 case glslang::EbtFloat16:
4960 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4961 break;
4962#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004963 case glslang::EbtBool:
4964 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4965 break;
4966 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004967 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004968 break;
4969 }
4970 ++nextConst;
4971 }
4972 } else {
4973 // we have a non-aggregate (scalar) constant
4974 bool zero = nextConst >= consts.size();
4975 spv::Id scalar = 0;
4976 switch (glslangType.getBasicType()) {
4977 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004978 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004979 break;
4980 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004981 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004982 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004983 case glslang::EbtInt64:
4984 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4985 break;
4986 case glslang::EbtUint64:
4987 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4988 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004989 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004990 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004991 break;
4992 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004993 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004995#ifdef AMD_EXTENSIONS
4996 case glslang::EbtFloat16:
4997 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4998 break;
4999#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005000 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005001 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005002 break;
5003 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005004 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005005 break;
5006 }
5007 ++nextConst;
5008 return scalar;
5009 }
5010
5011 return builder.makeCompositeConstant(typeId, spvConsts);
5012}
5013
John Kessenich7c1aa102015-10-15 13:29:11 -06005014// Return true if the node is a constant or symbol whose reading has no
5015// non-trivial observable cost or effect.
5016bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5017{
5018 // don't know what this is
5019 if (node == nullptr)
5020 return false;
5021
5022 // a constant is safe
5023 if (node->getAsConstantUnion() != nullptr)
5024 return true;
5025
5026 // not a symbol means non-trivial
5027 if (node->getAsSymbolNode() == nullptr)
5028 return false;
5029
5030 // a symbol, depends on what's being read
5031 switch (node->getType().getQualifier().storage) {
5032 case glslang::EvqTemporary:
5033 case glslang::EvqGlobal:
5034 case glslang::EvqIn:
5035 case glslang::EvqInOut:
5036 case glslang::EvqConst:
5037 case glslang::EvqConstReadOnly:
5038 case glslang::EvqUniform:
5039 return true;
5040 default:
5041 return false;
5042 }
qining25262b32016-05-06 17:25:16 -04005043}
John Kessenich7c1aa102015-10-15 13:29:11 -06005044
5045// A node is trivial if it is a single operation with no side effects.
5046// Error on the side of saying non-trivial.
5047// Return true if trivial.
5048bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5049{
5050 if (node == nullptr)
5051 return false;
5052
5053 // symbols and constants are trivial
5054 if (isTrivialLeaf(node))
5055 return true;
5056
5057 // otherwise, it needs to be a simple operation or one or two leaf nodes
5058
5059 // not a simple operation
5060 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5061 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5062 if (binaryNode == nullptr && unaryNode == nullptr)
5063 return false;
5064
5065 // not on leaf nodes
5066 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5067 return false;
5068
5069 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5070 return false;
5071 }
5072
5073 switch (node->getAsOperator()->getOp()) {
5074 case glslang::EOpLogicalNot:
5075 case glslang::EOpConvIntToBool:
5076 case glslang::EOpConvUintToBool:
5077 case glslang::EOpConvFloatToBool:
5078 case glslang::EOpConvDoubleToBool:
5079 case glslang::EOpEqual:
5080 case glslang::EOpNotEqual:
5081 case glslang::EOpLessThan:
5082 case glslang::EOpGreaterThan:
5083 case glslang::EOpLessThanEqual:
5084 case glslang::EOpGreaterThanEqual:
5085 case glslang::EOpIndexDirect:
5086 case glslang::EOpIndexDirectStruct:
5087 case glslang::EOpLogicalXor:
5088 case glslang::EOpAny:
5089 case glslang::EOpAll:
5090 return true;
5091 default:
5092 return false;
5093 }
5094}
5095
5096// Emit short-circuiting code, where 'right' is never evaluated unless
5097// the left side is true (for &&) or false (for ||).
5098spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5099{
5100 spv::Id boolTypeId = builder.makeBoolType();
5101
5102 // emit left operand
5103 builder.clearAccessChain();
5104 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005105 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005106
5107 // Operands to accumulate OpPhi operands
5108 std::vector<spv::Id> phiOperands;
5109 // accumulate left operand's phi information
5110 phiOperands.push_back(leftId);
5111 phiOperands.push_back(builder.getBuildPoint()->getId());
5112
5113 // Make the two kinds of operation symmetric with a "!"
5114 // || => emit "if (! left) result = right"
5115 // && => emit "if ( left) result = right"
5116 //
5117 // TODO: this runtime "not" for || could be avoided by adding functionality
5118 // to 'builder' to have an "else" without an "then"
5119 if (op == glslang::EOpLogicalOr)
5120 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5121
5122 // make an "if" based on the left value
5123 spv::Builder::If ifBuilder(leftId, builder);
5124
5125 // emit right operand as the "then" part of the "if"
5126 builder.clearAccessChain();
5127 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005128 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005129
5130 // accumulate left operand's phi information
5131 phiOperands.push_back(rightId);
5132 phiOperands.push_back(builder.getBuildPoint()->getId());
5133
5134 // finish the "if"
5135 ifBuilder.makeEndIf();
5136
5137 // phi together the two results
5138 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5139}
5140
Rex Xu9d93a232016-05-05 12:30:44 +08005141// Return type Id of the imported set of extended instructions corresponds to the name.
5142// Import this set if it has not been imported yet.
5143spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5144{
5145 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5146 return extBuiltinMap[name];
5147 else {
Rex Xu51596642016-09-21 18:56:12 +08005148 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005149 spv::Id extBuiltins = builder.import(name);
5150 extBuiltinMap[name] = extBuiltins;
5151 return extBuiltins;
5152 }
5153}
5154
John Kessenich140f3df2015-06-26 16:58:36 -06005155}; // end anonymous namespace
5156
5157namespace glslang {
5158
John Kessenich68d78fd2015-07-12 19:28:10 -06005159void GetSpirvVersion(std::string& version)
5160{
John Kessenich9e55f632015-07-15 10:03:39 -06005161 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005162 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005163 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005164 version = buf;
5165}
5166
John Kessenich140f3df2015-06-26 16:58:36 -06005167// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005168void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005169{
5170 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005171 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005172 for (int i = 0; i < (int)spirv.size(); ++i) {
5173 unsigned int word = spirv[i];
5174 out.write((const char*)&word, 4);
5175 }
5176 out.close();
5177}
5178
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005179// Write SPIR-V out to a text file with 32-bit hexadecimal words
5180void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5181{
5182 std::ofstream out;
5183 out.open(baseName, std::ios::binary | std::ios::out);
5184 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5185 const int WORDS_PER_LINE = 8;
5186 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5187 out << "\t";
5188 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5189 const unsigned int word = spirv[i + j];
5190 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5191 if (i + j + 1 < (int)spirv.size()) {
5192 out << ",";
5193 }
5194 }
5195 out << std::endl;
5196 }
5197 out.close();
5198}
5199
John Kessenich140f3df2015-06-26 16:58:36 -06005200//
5201// Set up the glslang traversal
5202//
5203void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5204{
Lei Zhang17535f72016-05-04 15:55:59 -04005205 spv::SpvBuildLogger logger;
5206 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005207}
5208
Lei Zhang17535f72016-05-04 15:55:59 -04005209void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005210{
John Kessenich140f3df2015-06-26 16:58:36 -06005211 TIntermNode* root = intermediate.getTreeRoot();
5212
5213 if (root == 0)
5214 return;
5215
5216 glslang::GetThreadPoolAllocator().push();
5217
Lei Zhang17535f72016-05-04 15:55:59 -04005218 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005219 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005220 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005221 it.dumpSpv(spirv);
5222
5223 glslang::GetThreadPoolAllocator().pop();
5224}
5225
5226}; // end namespace glslang