blob: 5e3dc520e8d92b1bd28203c8706f8f0c9b319b4b [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 Xub7072052016-09-26 15:53:40 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, 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);
2018 builder.addCapability(spv::CapabilityFloat16);
2019 spvType = builder.makeFloatType(16);
2020 break;
2021#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002022 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002023 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2024 // a 32-bit int where non-0 means true.
2025 if (explicitLayout != glslang::ElpNone)
2026 spvType = builder.makeUintType(32);
2027 else
2028 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002029 break;
2030 case glslang::EbtInt:
2031 spvType = builder.makeIntType(32);
2032 break;
2033 case glslang::EbtUint:
2034 spvType = builder.makeUintType(32);
2035 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002036 case glslang::EbtInt64:
2037 builder.addCapability(spv::CapabilityInt64);
2038 spvType = builder.makeIntType(64);
2039 break;
2040 case glslang::EbtUint64:
2041 builder.addCapability(spv::CapabilityInt64);
2042 spvType = builder.makeUintType(64);
2043 break;
John Kessenich426394d2015-07-23 10:22:48 -06002044 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002045 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002046 spvType = builder.makeUintType(32);
2047 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002048 case glslang::EbtSampler:
2049 {
2050 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002051 if (sampler.sampler) {
2052 // pure sampler
2053 spvType = builder.makeSamplerType();
2054 } else {
2055 // an image is present, make its type
2056 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2057 sampler.image ? 2 : 1, TranslateImageFormat(type));
2058 if (sampler.combined) {
2059 // already has both image and sampler, make the combined type
2060 spvType = builder.makeSampledImageType(spvType);
2061 }
John Kessenich55e7d112015-11-15 21:33:39 -07002062 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002063 }
John Kessenich140f3df2015-06-26 16:58:36 -06002064 break;
2065 case glslang::EbtStruct:
2066 case glslang::EbtBlock:
2067 {
2068 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002069 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002070
2071 // Try to share structs for different layouts, but not yet for other
2072 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002073 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002074 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002075 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002076 break;
2077
2078 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002079 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002080 memberRemapper[glslangMembers].resize(glslangMembers->size());
2081 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002082 }
2083 break;
2084 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002085 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002086 break;
2087 }
2088
2089 if (type.isMatrix())
2090 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2091 else {
2092 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2093 if (type.getVectorSize() > 1)
2094 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2095 }
2096
2097 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002098 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2099
John Kessenichc9a80832015-09-12 12:17:44 -06002100 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002101 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002102 // We need to decorate array strides for types needing explicit layout, except blocks.
2103 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002104 // Use a dummy glslang type for querying internal strides of
2105 // arrays of arrays, but using just a one-dimensional array.
2106 glslang::TType simpleArrayType(type, 0); // deference type of the array
2107 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2108 simpleArrayType.getArraySizes().dereference();
2109
2110 // Will compute the higher-order strides here, rather than making a whole
2111 // pile of types and doing repetitive recursion on their contents.
2112 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2113 }
John Kessenichf8842e52016-01-04 19:22:56 -07002114
2115 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002116 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002117 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002118 if (stride > 0)
2119 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002120 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002121 }
2122 } else {
2123 // single-dimensional array, and don't yet have stride
2124
John Kessenichf8842e52016-01-04 19:22:56 -07002125 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002126 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2127 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002128 }
John Kessenich31ed4832015-09-09 17:51:38 -06002129
John Kessenichc9a80832015-09-12 12:17:44 -06002130 // Do the outer dimension, which might not be known for a runtime-sized array
2131 if (type.isRuntimeSizedArray()) {
2132 spvType = builder.makeRuntimeArray(spvType);
2133 } else {
2134 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002135 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002136 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002137 if (stride > 0)
2138 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002139 }
2140
2141 return spvType;
2142}
2143
John Kessenich6090df02016-06-30 21:18:02 -06002144// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2145// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2146// Mutually recursive with convertGlslangToSpvType().
2147spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2148 const glslang::TTypeList* glslangMembers,
2149 glslang::TLayoutPacking explicitLayout,
2150 const glslang::TQualifier& qualifier)
2151{
2152 // Create a vector of struct types for SPIR-V to consume
2153 std::vector<spv::Id> spvMembers;
2154 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2155 int locationOffset = 0; // for use across struct members, when they are called recursively
2156 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2157 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2158 if (glslangMember.hiddenMember()) {
2159 ++memberDelta;
2160 if (type.getBasicType() == glslang::EbtBlock)
2161 memberRemapper[glslangMembers][i] = -1;
2162 } else {
2163 if (type.getBasicType() == glslang::EbtBlock)
2164 memberRemapper[glslangMembers][i] = i - memberDelta;
2165 // modify just this child's view of the qualifier
2166 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2167 InheritQualifiers(memberQualifier, qualifier);
2168
2169 // manually inherit location; it's more complex
2170 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2171 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2172 if (qualifier.hasLocation())
2173 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2174
2175 // recurse
2176 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2177 }
2178 }
2179
2180 // Make the SPIR-V type
2181 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002182 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002183 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2184
2185 // Decorate it
2186 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2187
2188 return spvType;
2189}
2190
2191void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2192 const glslang::TTypeList* glslangMembers,
2193 glslang::TLayoutPacking explicitLayout,
2194 const glslang::TQualifier& qualifier,
2195 spv::Id spvType)
2196{
2197 // Name and decorate the non-hidden members
2198 int offset = -1;
2199 int locationOffset = 0; // for use within the members of this struct
2200 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2201 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2202 int member = i;
2203 if (type.getBasicType() == glslang::EbtBlock)
2204 member = memberRemapper[glslangMembers][i];
2205
2206 // modify just this child's view of the qualifier
2207 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2208 InheritQualifiers(memberQualifier, qualifier);
2209
2210 // using -1 above to indicate a hidden member
2211 if (member >= 0) {
2212 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2213 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2214 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2215 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2216 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2217 if (type.getBasicType() == glslang::EbtBlock) {
2218 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2219 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2220 }
2221 }
2222 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2223
2224 if (qualifier.storage == glslang::EvqBuffer) {
2225 std::vector<spv::Decoration> memory;
2226 TranslateMemoryDecoration(memberQualifier, memory);
2227 for (unsigned int i = 0; i < memory.size(); ++i)
2228 addMemberDecoration(spvType, member, memory[i]);
2229 }
2230
John Kessenich2f47bc92016-06-30 21:47:35 -06002231 // Compute location decoration; tricky based on whether inheritance is at play and
2232 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002233 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2234 // probably move to the linker stage of the front end proper, and just have the
2235 // answer sitting already distributed throughout the individual member locations.
2236 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002237 // Ignore member locations if the container is an array, as that's
2238 // ill-specified and decisions have been made to not allow this anyway.
2239 // The object itself must have a location, and that comes out from decorating the object,
2240 // not the type (this code decorates types).
2241 if (! type.isArray()) {
2242 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2243 // struct members should not have explicit locations
2244 assert(type.getBasicType() != glslang::EbtStruct);
2245 location = memberQualifier.layoutLocation;
2246 } else if (type.getBasicType() != glslang::EbtBlock) {
2247 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2248 // The members, and their nested types, must not themselves have Location decorations.
2249 } else if (qualifier.hasLocation()) // inheritance
2250 location = qualifier.layoutLocation + locationOffset;
2251 }
John Kessenich6090df02016-06-30 21:18:02 -06002252 if (location >= 0)
2253 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2254
John Kessenich2f47bc92016-06-30 21:47:35 -06002255 if (qualifier.hasLocation()) // track for upcoming inheritance
2256 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2257
John Kessenich6090df02016-06-30 21:18:02 -06002258 // component, XFB, others
2259 if (glslangMember.getQualifier().hasComponent())
2260 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2261 if (glslangMember.getQualifier().hasXfbOffset())
2262 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2263 else if (explicitLayout != glslang::ElpNone) {
2264 // figure out what to do with offset, which is accumulating
2265 int nextOffset;
2266 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2267 if (offset >= 0)
2268 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2269 offset = nextOffset;
2270 }
2271
2272 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2273 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2274
2275 // built-in variable decorations
2276 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002277 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002278 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2279 }
2280 }
2281
2282 // Decorate the structure
2283 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2284 addDecoration(spvType, TranslateBlockDecoration(type));
2285 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2286 builder.addCapability(spv::CapabilityGeometryStreams);
2287 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2288 }
2289 if (glslangIntermediate->getXfbMode()) {
2290 builder.addCapability(spv::CapabilityTransformFeedback);
2291 if (type.getQualifier().hasXfbStride())
2292 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2293 if (type.getQualifier().hasXfbBuffer())
2294 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2295 }
2296}
2297
John Kessenich6c292d32016-02-15 20:58:50 -07002298// Turn the expression forming the array size into an id.
2299// This is not quite trivial, because of specialization constants.
2300// Sometimes, a raw constant is turned into an Id, and sometimes
2301// a specialization constant expression is.
2302spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2303{
2304 // First, see if this is sized with a node, meaning a specialization constant:
2305 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2306 if (specNode != nullptr) {
2307 builder.clearAccessChain();
2308 specNode->traverse(this);
2309 return accessChainLoad(specNode->getAsTyped()->getType());
2310 }
qining25262b32016-05-06 17:25:16 -04002311
John Kessenich6c292d32016-02-15 20:58:50 -07002312 // Otherwise, need a compile-time (front end) size, get it:
2313 int size = arraySizes.getDimSize(dim);
2314 assert(size > 0);
2315 return builder.makeUintConstant(size);
2316}
2317
John Kessenich103bef92016-02-08 21:38:15 -07002318// Wrap the builder's accessChainLoad to:
2319// - localize handling of RelaxedPrecision
2320// - use the SPIR-V inferred type instead of another conversion of the glslang type
2321// (avoids unnecessary work and possible type punning for structures)
2322// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002323spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2324{
John Kessenich103bef92016-02-08 21:38:15 -07002325 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2326 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2327
2328 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002329 if (type.getBasicType() == glslang::EbtBool) {
2330 if (builder.isScalarType(nominalTypeId)) {
2331 // Conversion for bool
2332 spv::Id boolType = builder.makeBoolType();
2333 if (nominalTypeId != boolType)
2334 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2335 } else if (builder.isVectorType(nominalTypeId)) {
2336 // Conversion for bvec
2337 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2338 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2339 if (nominalTypeId != bvecType)
2340 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2341 }
2342 }
John Kessenich103bef92016-02-08 21:38:15 -07002343
2344 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002345}
2346
Rex Xu27253232016-02-23 17:51:09 +08002347// Wrap the builder's accessChainStore to:
2348// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002349//
2350// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002351void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2352{
2353 // Need to convert to abstract types when necessary
2354 if (type.getBasicType() == glslang::EbtBool) {
2355 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2356
2357 if (builder.isScalarType(nominalTypeId)) {
2358 // Conversion for bool
2359 spv::Id boolType = builder.makeBoolType();
2360 if (nominalTypeId != boolType) {
2361 spv::Id zero = builder.makeUintConstant(0);
2362 spv::Id one = builder.makeUintConstant(1);
2363 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2364 }
2365 } else if (builder.isVectorType(nominalTypeId)) {
2366 // Conversion for bvec
2367 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2368 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2369 if (nominalTypeId != bvecType) {
2370 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2371 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2372 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2373 }
2374 }
2375 }
2376
2377 builder.accessChainStore(rvalue);
2378}
2379
John Kessenich4bf71552016-09-02 11:20:21 -06002380// For storing when types match at the glslang level, but not might match at the
2381// SPIR-V level.
2382//
2383// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002384// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002385// as in a member-decorated way.
2386//
2387// NOTE: This function can handle any store request; if it's not special it
2388// simplifies to a simple OpStore.
2389//
2390// Implicitly uses the existing builder.accessChain as the storage target.
2391void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2392{
John Kessenichb3e24e42016-09-11 12:33:43 -06002393 // we only do the complex path here if it's an aggregate
2394 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002395 accessChainStore(type, rValue);
2396 return;
2397 }
2398
John Kessenichb3e24e42016-09-11 12:33:43 -06002399 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002400 spv::Id rType = builder.getTypeId(rValue);
2401 spv::Id lValue = builder.accessChainGetLValue();
2402 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2403 if (lType == rType) {
2404 accessChainStore(type, rValue);
2405 return;
2406 }
2407
John Kessenichb3e24e42016-09-11 12:33:43 -06002408 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002409 // where the two types were the same type in GLSL. This requires member
2410 // by member copy, recursively.
2411
John Kessenichb3e24e42016-09-11 12:33:43 -06002412 // If an array, copy element by element.
2413 if (type.isArray()) {
2414 glslang::TType glslangElementType(type, 0);
2415 spv::Id elementRType = builder.getContainedTypeId(rType);
2416 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2417 // get the source member
2418 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002419
John Kessenichb3e24e42016-09-11 12:33:43 -06002420 // set up the target storage
2421 builder.clearAccessChain();
2422 builder.setAccessChainLValue(lValue);
2423 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002424
John Kessenichb3e24e42016-09-11 12:33:43 -06002425 // store the member
2426 multiTypeStore(glslangElementType, elementRValue);
2427 }
2428 } else {
2429 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002430
John Kessenichb3e24e42016-09-11 12:33:43 -06002431 // loop over structure members
2432 const glslang::TTypeList& members = *type.getStruct();
2433 for (int m = 0; m < (int)members.size(); ++m) {
2434 const glslang::TType& glslangMemberType = *members[m].type;
2435
2436 // get the source member
2437 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2438 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2439
2440 // set up the target storage
2441 builder.clearAccessChain();
2442 builder.setAccessChainLValue(lValue);
2443 builder.accessChainPush(builder.makeIntConstant(m));
2444
2445 // store the member
2446 multiTypeStore(glslangMemberType, memberRValue);
2447 }
John Kessenich4bf71552016-09-02 11:20:21 -06002448 }
2449}
2450
John Kessenichf85e8062015-12-19 13:57:10 -07002451// Decide whether or not this type should be
2452// decorated with offsets and strides, and if so
2453// whether std140 or std430 rules should be applied.
2454glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002455{
John Kessenichf85e8062015-12-19 13:57:10 -07002456 // has to be a block
2457 if (type.getBasicType() != glslang::EbtBlock)
2458 return glslang::ElpNone;
2459
2460 // has to be a uniform or buffer block
2461 if (type.getQualifier().storage != glslang::EvqUniform &&
2462 type.getQualifier().storage != glslang::EvqBuffer)
2463 return glslang::ElpNone;
2464
2465 // return the layout to use
2466 switch (type.getQualifier().layoutPacking) {
2467 case glslang::ElpStd140:
2468 case glslang::ElpStd430:
2469 return type.getQualifier().layoutPacking;
2470 default:
2471 return glslang::ElpNone;
2472 }
John Kessenich31ed4832015-09-09 17:51:38 -06002473}
2474
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002475// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002476int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002477{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002478 int size;
John Kessenich49987892015-12-29 17:11:44 -07002479 int stride;
2480 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002481
2482 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002483}
2484
John Kessenich49987892015-12-29 17:11:44 -07002485// 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 -07002486// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002487int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002488{
John Kessenich49987892015-12-29 17:11:44 -07002489 glslang::TType elementType;
2490 elementType.shallowCopy(matrixType);
2491 elementType.clearArraySizes();
2492
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002493 int size;
John Kessenich49987892015-12-29 17:11:44 -07002494 int stride;
2495 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2496
2497 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002498}
2499
John Kessenich5e4b1242015-08-06 22:53:06 -06002500// Given a member type of a struct, realign the current offset for it, and compute
2501// the next (not yet aligned) offset for the next member, which will get aligned
2502// on the next call.
2503// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2504// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2505// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002506void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002507 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002508{
2509 // this will get a positive value when deemed necessary
2510 nextOffset = -1;
2511
John Kessenich5e4b1242015-08-06 22:53:06 -06002512 // override anything in currentOffset with user-set offset
2513 if (memberType.getQualifier().hasOffset())
2514 currentOffset = memberType.getQualifier().layoutOffset;
2515
2516 // It could be that current linker usage in glslang updated all the layoutOffset,
2517 // in which case the following code does not matter. But, that's not quite right
2518 // once cross-compilation unit GLSL validation is done, as the original user
2519 // settings are needed in layoutOffset, and then the following will come into play.
2520
John Kessenichf85e8062015-12-19 13:57:10 -07002521 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002522 if (! memberType.getQualifier().hasOffset())
2523 currentOffset = -1;
2524
2525 return;
2526 }
2527
John Kessenichf85e8062015-12-19 13:57:10 -07002528 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002529 if (currentOffset < 0)
2530 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002531
John Kessenich5e4b1242015-08-06 22:53:06 -06002532 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2533 // but possibly not yet correctly aligned.
2534
2535 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002536 int dummyStride;
2537 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002538 glslang::RoundToPow2(currentOffset, memberAlignment);
2539 nextOffset = currentOffset + memberSize;
2540}
2541
David Netoa901ffe2016-06-08 14:11:40 +01002542void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002543{
David Netoa901ffe2016-06-08 14:11:40 +01002544 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2545 switch (glslangBuiltIn)
2546 {
2547 case glslang::EbvClipDistance:
2548 case glslang::EbvCullDistance:
2549 case glslang::EbvPointSize:
2550 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2551 // Alternately, we could just call this for any glslang built-in, since the
2552 // capability already guards against duplicates.
2553 TranslateBuiltInDecoration(glslangBuiltIn, false);
2554 break;
2555 default:
2556 // Capabilities were already generated when the struct was declared.
2557 break;
2558 }
John Kessenichebb50532016-05-16 19:22:05 -06002559}
2560
John Kessenich6fccb3c2016-09-19 16:01:41 -06002561bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002562{
John Kessenicheee9d532016-09-19 18:09:30 -06002563 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002564}
2565
2566// Make all the functions, skeletally, without actually visiting their bodies.
2567void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2568{
2569 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2570 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002571 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002572 continue;
2573
2574 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002575 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002576 //
qining25262b32016-05-06 17:25:16 -04002577 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002578 // function. What it is an address of varies:
2579 //
John Kessenich4bf71552016-09-02 11:20:21 -06002580 // - "in" parameters not marked as "const" can be written to without modifying the calling
2581 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002582 //
2583 // - "const in" parameters can just be the r-value, as no writes need occur.
2584 //
John Kessenich4bf71552016-09-02 11:20:21 -06002585 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2586 // 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 -06002587
2588 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002589 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002590 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2591
2592 for (int p = 0; p < (int)parameters.size(); ++p) {
2593 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2594 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002595 if (paramType.isOpaque())
2596 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2597 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002598 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2599 else
John Kessenich4bf71552016-09-02 11:20:21 -06002600 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002601 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002602 paramTypes.push_back(typeId);
2603 }
2604
2605 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002606 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2607 convertGlslangToSpvType(glslFunction->getType()),
2608 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002609
2610 // Track function to emit/call later
2611 functionMap[glslFunction->getName().c_str()] = function;
2612
2613 // Set the parameter id's
2614 for (int p = 0; p < (int)parameters.size(); ++p) {
2615 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2616 // give a name too
2617 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2618 }
2619 }
2620}
2621
2622// Process all the initializers, while skipping the functions and link objects
2623void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2624{
2625 builder.setBuildPoint(shaderEntry->getLastBlock());
2626 for (int i = 0; i < (int)initializers.size(); ++i) {
2627 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2628 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2629
2630 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002631 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002632 initializer->traverse(this);
2633 }
2634 }
2635}
2636
2637// Process all the functions, while skipping initializers.
2638void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2639{
2640 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2641 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002642 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002643 node->traverse(this);
2644 }
2645}
2646
2647void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2648{
qining25262b32016-05-06 17:25:16 -04002649 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002650 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002651 currentFunction = functionMap[node->getName().c_str()];
2652 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002653 builder.setBuildPoint(functionBlock);
2654}
2655
Rex Xu04db3f52015-09-16 11:44:02 +08002656void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002657{
Rex Xufc618912015-09-09 16:42:49 +08002658 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002659
2660 glslang::TSampler sampler = {};
2661 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002662 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002663 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2664 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2665 }
2666
John Kessenich140f3df2015-06-26 16:58:36 -06002667 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2668 builder.clearAccessChain();
2669 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002670
2671 // Special case l-value operands
2672 bool lvalue = false;
2673 switch (node.getOp()) {
2674 case glslang::EOpImageAtomicAdd:
2675 case glslang::EOpImageAtomicMin:
2676 case glslang::EOpImageAtomicMax:
2677 case glslang::EOpImageAtomicAnd:
2678 case glslang::EOpImageAtomicOr:
2679 case glslang::EOpImageAtomicXor:
2680 case glslang::EOpImageAtomicExchange:
2681 case glslang::EOpImageAtomicCompSwap:
2682 if (i == 0)
2683 lvalue = true;
2684 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002685 case glslang::EOpSparseImageLoad:
2686 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2687 lvalue = true;
2688 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002689 case glslang::EOpSparseTexture:
2690 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2691 lvalue = true;
2692 break;
2693 case glslang::EOpSparseTextureClamp:
2694 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2695 lvalue = true;
2696 break;
2697 case glslang::EOpSparseTextureLod:
2698 case glslang::EOpSparseTextureOffset:
2699 if (i == 3)
2700 lvalue = true;
2701 break;
2702 case glslang::EOpSparseTextureFetch:
2703 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2704 lvalue = true;
2705 break;
2706 case glslang::EOpSparseTextureFetchOffset:
2707 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2708 lvalue = true;
2709 break;
2710 case glslang::EOpSparseTextureLodOffset:
2711 case glslang::EOpSparseTextureGrad:
2712 case glslang::EOpSparseTextureOffsetClamp:
2713 if (i == 4)
2714 lvalue = true;
2715 break;
2716 case glslang::EOpSparseTextureGradOffset:
2717 case glslang::EOpSparseTextureGradClamp:
2718 if (i == 5)
2719 lvalue = true;
2720 break;
2721 case glslang::EOpSparseTextureGradOffsetClamp:
2722 if (i == 6)
2723 lvalue = true;
2724 break;
2725 case glslang::EOpSparseTextureGather:
2726 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2727 lvalue = true;
2728 break;
2729 case glslang::EOpSparseTextureGatherOffset:
2730 case glslang::EOpSparseTextureGatherOffsets:
2731 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2732 lvalue = true;
2733 break;
Rex Xufc618912015-09-09 16:42:49 +08002734 default:
2735 break;
2736 }
2737
Rex Xu6b86d492015-09-16 17:48:22 +08002738 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002739 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002740 else
John Kessenich32cfd492016-02-02 12:37:46 -07002741 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002742 }
2743}
2744
John Kessenichfc51d282015-08-19 13:34:18 -06002745void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002746{
John Kessenichfc51d282015-08-19 13:34:18 -06002747 builder.clearAccessChain();
2748 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002749 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002750}
John Kessenich140f3df2015-06-26 16:58:36 -06002751
John Kessenichfc51d282015-08-19 13:34:18 -06002752spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2753{
Rex Xufc618912015-09-09 16:42:49 +08002754 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002755 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002756 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002757 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002758
John Kessenichfc51d282015-08-19 13:34:18 -06002759 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002760 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2761 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2762 std::vector<spv::Id> arguments;
2763 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002764 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002765 else
2766 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002767 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002768
2769 spv::Builder::TextureParameters params = { };
2770 params.sampler = arguments[0];
2771
Rex Xu04db3f52015-09-16 11:44:02 +08002772 glslang::TCrackedTextureOp cracked;
2773 node->crackTexture(sampler, cracked);
2774
John Kessenichfc51d282015-08-19 13:34:18 -06002775 // Check for queries
2776 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002777 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2778 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002779 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002780
John Kessenichfc51d282015-08-19 13:34:18 -06002781 switch (node->getOp()) {
2782 case glslang::EOpImageQuerySize:
2783 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002784 if (arguments.size() > 1) {
2785 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002787 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002788 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002789 case glslang::EOpImageQuerySamples:
2790 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002791 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002792 case glslang::EOpTextureQueryLod:
2793 params.coords = arguments[1];
2794 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2795 case glslang::EOpTextureQueryLevels:
2796 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002797 case glslang::EOpSparseTexelsResident:
2798 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002799 default:
2800 assert(0);
2801 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002802 }
John Kessenich140f3df2015-06-26 16:58:36 -06002803 }
2804
Rex Xufc618912015-09-09 16:42:49 +08002805 // Check for image functions other than queries
2806 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002807 std::vector<spv::Id> operands;
2808 auto opIt = arguments.begin();
2809 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002810
2811 // Handle subpass operations
2812 // TODO: GLSL should change to have the "MS" only on the type rather than the
2813 // built-in function.
2814 if (cracked.subpass) {
2815 // add on the (0,0) coordinate
2816 spv::Id zero = builder.makeIntConstant(0);
2817 std::vector<spv::Id> comps;
2818 comps.push_back(zero);
2819 comps.push_back(zero);
2820 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2821 if (sampler.ms) {
2822 operands.push_back(spv::ImageOperandsSampleMask);
2823 operands.push_back(*(opIt++));
2824 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002825 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002826 }
2827
John Kessenich56bab042015-09-16 10:54:31 -06002828 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002829 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002830 if (sampler.ms) {
2831 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002832 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002833 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002834 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2835 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002836 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002837 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002838 if (sampler.ms) {
2839 operands.push_back(*(opIt + 1));
2840 operands.push_back(spv::ImageOperandsSampleMask);
2841 operands.push_back(*opIt);
2842 } else
2843 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002844 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002845 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2846 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002847 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002848 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2849 builder.addCapability(spv::CapabilitySparseResidency);
2850 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2851 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2852
2853 if (sampler.ms) {
2854 operands.push_back(spv::ImageOperandsSampleMask);
2855 operands.push_back(*opIt++);
2856 }
2857
2858 // Create the return type that was a special structure
2859 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002860 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002861 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2862 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2863
2864 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2865
2866 // Decode the return type
2867 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2868 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002869 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002870 // Process image atomic operations
2871
2872 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2873 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002874 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002875
John Kessenich8c8505c2016-07-26 12:50:38 -06002876 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002877 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002878
2879 std::vector<spv::Id> operands;
2880 operands.push_back(pointer);
2881 for (; opIt != arguments.end(); ++opIt)
2882 operands.push_back(*opIt);
2883
John Kessenich8c8505c2016-07-26 12:50:38 -06002884 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002885 }
2886 }
2887
2888 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002889 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002890 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2891
John Kessenichfc51d282015-08-19 13:34:18 -06002892 // check for bias argument
2893 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002894 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002895 int nonBiasArgCount = 2;
2896 if (cracked.offset)
2897 ++nonBiasArgCount;
2898 if (cracked.grad)
2899 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002900 if (cracked.lodClamp)
2901 ++nonBiasArgCount;
2902 if (sparse)
2903 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002904
2905 if ((int)arguments.size() > nonBiasArgCount)
2906 bias = true;
2907 }
2908
John Kessenicha5c33d62016-06-02 23:45:21 -06002909 // See if the sampler param should really be just the SPV image part
2910 if (cracked.fetch) {
2911 // a fetch needs to have the image extracted first
2912 if (builder.isSampledImage(params.sampler))
2913 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2914 }
2915
John Kessenichfc51d282015-08-19 13:34:18 -06002916 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002917
John Kessenichfc51d282015-08-19 13:34:18 -06002918 params.coords = arguments[1];
2919 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002920 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002921
2922 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002923 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002924 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002925 ++extraArgs;
2926 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002927 params.Dref = arguments[2];
2928 ++extraArgs;
2929 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002930 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002931 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002932 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002933 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002934 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002935 dRefComp = builder.getNumComponents(params.coords) - 1;
2936 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002937 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2938 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002939
2940 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002941 if (cracked.lod) {
2942 params.lod = arguments[2];
2943 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002944 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2945 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2946 noImplicitLod = true;
2947 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002948
2949 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002950 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002951 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002952 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002953 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002954
2955 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002956 if (cracked.grad) {
2957 params.gradX = arguments[2 + extraArgs];
2958 params.gradY = arguments[3 + extraArgs];
2959 extraArgs += 2;
2960 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002961
2962 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002963 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002964 params.offset = arguments[2 + extraArgs];
2965 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002966 } else if (cracked.offsets) {
2967 params.offsets = arguments[2 + extraArgs];
2968 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002969 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002970
2971 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002972 if (cracked.lodClamp) {
2973 params.lodClamp = arguments[2 + extraArgs];
2974 ++extraArgs;
2975 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002976
2977 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002978 if (sparse) {
2979 params.texelOut = arguments[2 + extraArgs];
2980 ++extraArgs;
2981 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002982
2983 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002984 if (bias) {
2985 params.bias = arguments[2 + extraArgs];
2986 ++extraArgs;
2987 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002988
2989 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002990 if (cracked.gather && ! sampler.shadow) {
2991 // default component is 0, if missing, otherwise an argument
2992 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002993 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002994 ++extraArgs;
2995 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002996 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002997 }
2998 }
John Kessenichfc51d282015-08-19 13:34:18 -06002999
John Kessenich65336482016-06-16 14:06:26 -06003000 // projective component (might not to move)
3001 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3002 // are divided by the last component of P."
3003 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3004 // unused components will appear after all used components."
3005 if (cracked.proj) {
3006 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3007 int projTargetComp;
3008 switch (sampler.dim) {
3009 case glslang::Esd1D: projTargetComp = 1; break;
3010 case glslang::Esd2D: projTargetComp = 2; break;
3011 case glslang::EsdRect: projTargetComp = 2; break;
3012 default: projTargetComp = projSourceComp; break;
3013 }
3014 // copy the projective coordinate if we have to
3015 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003016 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003017 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3018 projSourceComp);
3019 params.coords = builder.createCompositeInsert(projComp, params.coords,
3020 builder.getTypeId(params.coords), projTargetComp);
3021 }
3022 }
3023
John Kessenich8c8505c2016-07-26 12:50:38 -06003024 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003025}
3026
3027spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3028{
3029 // Grab the function's pointer from the previously created function
3030 spv::Function* function = functionMap[node->getName().c_str()];
3031 if (! function)
3032 return 0;
3033
3034 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3035 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3036
3037 // See comments in makeFunctions() for details about the semantics for parameter passing.
3038 //
3039 // These imply we need a four step process:
3040 // 1. Evaluate the arguments
3041 // 2. Allocate and make copies of in, out, and inout arguments
3042 // 3. Make the call
3043 // 4. Copy back the results
3044
3045 // 1. Evaluate the arguments
3046 std::vector<spv::Builder::AccessChain> lValues;
3047 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003048 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003050 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003051 // build l-value
3052 builder.clearAccessChain();
3053 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003054 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003055 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003056 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003057 // save l-value
3058 lValues.push_back(builder.getAccessChain());
3059 } else {
3060 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003061 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003062 }
3063 }
3064
3065 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3066 // copy the original into that space.
3067 //
3068 // Also, build up the list of actual arguments to pass in for the call
3069 int lValueCount = 0;
3070 int rValueCount = 0;
3071 std::vector<spv::Id> spvArgs;
3072 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003073 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003074 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003075 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003076 builder.setAccessChain(lValues[lValueCount]);
3077 arg = builder.accessChainGetLValue();
3078 ++lValueCount;
3079 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003080 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003081 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3082 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3083 // need to copy the input into output space
3084 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003085 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003086 builder.clearAccessChain();
3087 builder.setAccessChainLValue(arg);
3088 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003089 }
3090 ++lValueCount;
3091 } else {
3092 arg = rValues[rValueCount];
3093 ++rValueCount;
3094 }
3095 spvArgs.push_back(arg);
3096 }
3097
3098 // 3. Make the call.
3099 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003100 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003101
3102 // 4. Copy back out an "out" arguments.
3103 lValueCount = 0;
3104 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003105 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003106 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3107 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3108 spv::Id copy = builder.createLoad(spvArgs[a]);
3109 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003110 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003111 }
3112 ++lValueCount;
3113 }
3114 }
3115
3116 return result;
3117}
3118
3119// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003120spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3121 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003122 spv::Id typeId, spv::Id left, spv::Id right,
3123 glslang::TBasicType typeProxy, bool reduceComparison)
3124{
Rex Xu8ff43de2016-04-22 16:51:45 +08003125 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003126#ifdef AMD_EXTENSIONS
3127 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3128#else
John Kessenich140f3df2015-06-26 16:58:36 -06003129 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003130#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003131 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003132
3133 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003134 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003135 bool comparison = false;
3136
3137 switch (op) {
3138 case glslang::EOpAdd:
3139 case glslang::EOpAddAssign:
3140 if (isFloat)
3141 binOp = spv::OpFAdd;
3142 else
3143 binOp = spv::OpIAdd;
3144 break;
3145 case glslang::EOpSub:
3146 case glslang::EOpSubAssign:
3147 if (isFloat)
3148 binOp = spv::OpFSub;
3149 else
3150 binOp = spv::OpISub;
3151 break;
3152 case glslang::EOpMul:
3153 case glslang::EOpMulAssign:
3154 if (isFloat)
3155 binOp = spv::OpFMul;
3156 else
3157 binOp = spv::OpIMul;
3158 break;
3159 case glslang::EOpVectorTimesScalar:
3160 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003161 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003162 if (builder.isVector(right))
3163 std::swap(left, right);
3164 assert(builder.isScalar(right));
3165 needMatchingVectors = false;
3166 binOp = spv::OpVectorTimesScalar;
3167 } else
3168 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 case glslang::EOpVectorTimesMatrix:
3171 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003172 binOp = spv::OpVectorTimesMatrix;
3173 break;
3174 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003175 binOp = spv::OpMatrixTimesVector;
3176 break;
3177 case glslang::EOpMatrixTimesScalar:
3178 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003179 binOp = spv::OpMatrixTimesScalar;
3180 break;
3181 case glslang::EOpMatrixTimesMatrix:
3182 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003183 binOp = spv::OpMatrixTimesMatrix;
3184 break;
3185 case glslang::EOpOuterProduct:
3186 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003187 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003188 break;
3189
3190 case glslang::EOpDiv:
3191 case glslang::EOpDivAssign:
3192 if (isFloat)
3193 binOp = spv::OpFDiv;
3194 else if (isUnsigned)
3195 binOp = spv::OpUDiv;
3196 else
3197 binOp = spv::OpSDiv;
3198 break;
3199 case glslang::EOpMod:
3200 case glslang::EOpModAssign:
3201 if (isFloat)
3202 binOp = spv::OpFMod;
3203 else if (isUnsigned)
3204 binOp = spv::OpUMod;
3205 else
3206 binOp = spv::OpSMod;
3207 break;
3208 case glslang::EOpRightShift:
3209 case glslang::EOpRightShiftAssign:
3210 if (isUnsigned)
3211 binOp = spv::OpShiftRightLogical;
3212 else
3213 binOp = spv::OpShiftRightArithmetic;
3214 break;
3215 case glslang::EOpLeftShift:
3216 case glslang::EOpLeftShiftAssign:
3217 binOp = spv::OpShiftLeftLogical;
3218 break;
3219 case glslang::EOpAnd:
3220 case glslang::EOpAndAssign:
3221 binOp = spv::OpBitwiseAnd;
3222 break;
3223 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003224 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003225 binOp = spv::OpLogicalAnd;
3226 break;
3227 case glslang::EOpInclusiveOr:
3228 case glslang::EOpInclusiveOrAssign:
3229 binOp = spv::OpBitwiseOr;
3230 break;
3231 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003232 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003233 binOp = spv::OpLogicalOr;
3234 break;
3235 case glslang::EOpExclusiveOr:
3236 case glslang::EOpExclusiveOrAssign:
3237 binOp = spv::OpBitwiseXor;
3238 break;
3239 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003240 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003241 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003242 break;
3243
3244 case glslang::EOpLessThan:
3245 case glslang::EOpGreaterThan:
3246 case glslang::EOpLessThanEqual:
3247 case glslang::EOpGreaterThanEqual:
3248 case glslang::EOpEqual:
3249 case glslang::EOpNotEqual:
3250 case glslang::EOpVectorEqual:
3251 case glslang::EOpVectorNotEqual:
3252 comparison = true;
3253 break;
3254 default:
3255 break;
3256 }
3257
John Kessenich7c1aa102015-10-15 13:29:11 -06003258 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003259 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003260 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003261 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003262 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003263
3264 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003265 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003266 builder.promoteScalar(precision, left, right);
3267
qining25262b32016-05-06 17:25:16 -04003268 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3269 addDecoration(result, noContraction);
3270 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003271 }
3272
3273 if (! comparison)
3274 return 0;
3275
John Kessenich7c1aa102015-10-15 13:29:11 -06003276 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003277
John Kessenich4583b612016-08-07 19:14:22 -06003278 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3279 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003280 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003281
3282 switch (op) {
3283 case glslang::EOpLessThan:
3284 if (isFloat)
3285 binOp = spv::OpFOrdLessThan;
3286 else if (isUnsigned)
3287 binOp = spv::OpULessThan;
3288 else
3289 binOp = spv::OpSLessThan;
3290 break;
3291 case glslang::EOpGreaterThan:
3292 if (isFloat)
3293 binOp = spv::OpFOrdGreaterThan;
3294 else if (isUnsigned)
3295 binOp = spv::OpUGreaterThan;
3296 else
3297 binOp = spv::OpSGreaterThan;
3298 break;
3299 case glslang::EOpLessThanEqual:
3300 if (isFloat)
3301 binOp = spv::OpFOrdLessThanEqual;
3302 else if (isUnsigned)
3303 binOp = spv::OpULessThanEqual;
3304 else
3305 binOp = spv::OpSLessThanEqual;
3306 break;
3307 case glslang::EOpGreaterThanEqual:
3308 if (isFloat)
3309 binOp = spv::OpFOrdGreaterThanEqual;
3310 else if (isUnsigned)
3311 binOp = spv::OpUGreaterThanEqual;
3312 else
3313 binOp = spv::OpSGreaterThanEqual;
3314 break;
3315 case glslang::EOpEqual:
3316 case glslang::EOpVectorEqual:
3317 if (isFloat)
3318 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003319 else if (isBool)
3320 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003321 else
3322 binOp = spv::OpIEqual;
3323 break;
3324 case glslang::EOpNotEqual:
3325 case glslang::EOpVectorNotEqual:
3326 if (isFloat)
3327 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003328 else if (isBool)
3329 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003330 else
3331 binOp = spv::OpINotEqual;
3332 break;
3333 default:
3334 break;
3335 }
3336
qining25262b32016-05-06 17:25:16 -04003337 if (binOp != spv::OpNop) {
3338 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3339 addDecoration(result, noContraction);
3340 return builder.setPrecision(result, precision);
3341 }
John Kessenich140f3df2015-06-26 16:58:36 -06003342
3343 return 0;
3344}
3345
John Kessenich04bb8a02015-12-12 12:28:14 -07003346//
3347// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3348// These can be any of:
3349//
3350// matrix * scalar
3351// scalar * matrix
3352// matrix * matrix linear algebraic
3353// matrix * vector
3354// vector * matrix
3355// matrix * matrix componentwise
3356// matrix op matrix op in {+, -, /}
3357// matrix op scalar op in {+, -, /}
3358// scalar op matrix op in {+, -, /}
3359//
qining25262b32016-05-06 17:25:16 -04003360spv::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 -07003361{
3362 bool firstClass = true;
3363
3364 // First, handle first-class matrix operations (* and matrix/scalar)
3365 switch (op) {
3366 case spv::OpFDiv:
3367 if (builder.isMatrix(left) && builder.isScalar(right)) {
3368 // turn matrix / scalar into a multiply...
3369 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3370 op = spv::OpMatrixTimesScalar;
3371 } else
3372 firstClass = false;
3373 break;
3374 case spv::OpMatrixTimesScalar:
3375 if (builder.isMatrix(right))
3376 std::swap(left, right);
3377 assert(builder.isScalar(right));
3378 break;
3379 case spv::OpVectorTimesMatrix:
3380 assert(builder.isVector(left));
3381 assert(builder.isMatrix(right));
3382 break;
3383 case spv::OpMatrixTimesVector:
3384 assert(builder.isMatrix(left));
3385 assert(builder.isVector(right));
3386 break;
3387 case spv::OpMatrixTimesMatrix:
3388 assert(builder.isMatrix(left));
3389 assert(builder.isMatrix(right));
3390 break;
3391 default:
3392 firstClass = false;
3393 break;
3394 }
3395
qining25262b32016-05-06 17:25:16 -04003396 if (firstClass) {
3397 spv::Id result = builder.createBinOp(op, typeId, left, right);
3398 addDecoration(result, noContraction);
3399 return builder.setPrecision(result, precision);
3400 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003401
LoopDawg592860c2016-06-09 08:57:35 -06003402 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003403 // The result type of all of them is the same type as the (a) matrix operand.
3404 // The algorithm is to:
3405 // - break the matrix(es) into vectors
3406 // - smear any scalar to a vector
3407 // - do vector operations
3408 // - make a matrix out the vector results
3409 switch (op) {
3410 case spv::OpFAdd:
3411 case spv::OpFSub:
3412 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003413 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003414 case spv::OpFMul:
3415 {
3416 // one time set up...
3417 bool leftMat = builder.isMatrix(left);
3418 bool rightMat = builder.isMatrix(right);
3419 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3420 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3421 spv::Id scalarType = builder.getScalarTypeId(typeId);
3422 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3423 std::vector<spv::Id> results;
3424 spv::Id smearVec = spv::NoResult;
3425 if (builder.isScalar(left))
3426 smearVec = builder.smearScalar(precision, left, vecType);
3427 else if (builder.isScalar(right))
3428 smearVec = builder.smearScalar(precision, right, vecType);
3429
3430 // do each vector op
3431 for (unsigned int c = 0; c < numCols; ++c) {
3432 std::vector<unsigned int> indexes;
3433 indexes.push_back(c);
3434 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3435 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003436 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3437 addDecoration(result, noContraction);
3438 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003439 }
3440
3441 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003442 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003443 }
3444 default:
3445 assert(0);
3446 return spv::NoResult;
3447 }
3448}
3449
qining25262b32016-05-06 17:25:16 -04003450spv::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 -06003451{
3452 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003453 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003455 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003456#ifdef AMD_EXTENSIONS
3457 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3458#else
Rex Xu04db3f52015-09-16 11:44:02 +08003459 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003460#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003461
3462 switch (op) {
3463 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003464 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003465 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003466 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003467 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003468 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003469 unaryOp = spv::OpSNegate;
3470 break;
3471
3472 case glslang::EOpLogicalNot:
3473 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003474 unaryOp = spv::OpLogicalNot;
3475 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 case glslang::EOpBitwiseNot:
3477 unaryOp = spv::OpNot;
3478 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003479
John Kessenich140f3df2015-06-26 16:58:36 -06003480 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003481 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003484 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003485 break;
3486 case glslang::EOpTranspose:
3487 unaryOp = spv::OpTranspose;
3488 break;
3489
3490 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003504 break;
3505 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003506 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003507 break;
3508 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003509 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003510 break;
3511 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003512 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003513 break;
3514
3515 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 break;
3524 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
3527 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003528 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003529 break;
3530 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003531 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003532 break;
3533
3534 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003535 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003536 break;
3537 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003538 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003539 break;
3540
3541 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003542 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003543 break;
3544 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003545 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
3547 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003548 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003549 break;
3550 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003554 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003557 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003558 break;
3559
3560 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003561 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003562 break;
3563 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003564 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003565 break;
3566 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003567 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003568 break;
3569 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003570 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003571 break;
3572 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003573 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003574 break;
3575 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003576 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003577 break;
3578
3579 case glslang::EOpIsNan:
3580 unaryOp = spv::OpIsNan;
3581 break;
3582 case glslang::EOpIsInf:
3583 unaryOp = spv::OpIsInf;
3584 break;
LoopDawg592860c2016-06-09 08:57:35 -06003585 case glslang::EOpIsFinite:
3586 unaryOp = spv::OpIsFinite;
3587 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003588
Rex Xucbc426e2015-12-15 16:03:10 +08003589 case glslang::EOpFloatBitsToInt:
3590 case glslang::EOpFloatBitsToUint:
3591 case glslang::EOpIntBitsToFloat:
3592 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003593 case glslang::EOpDoubleBitsToInt64:
3594 case glslang::EOpDoubleBitsToUint64:
3595 case glslang::EOpInt64BitsToDouble:
3596 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003597 unaryOp = spv::OpBitcast;
3598 break;
3599
John Kessenich140f3df2015-06-26 16:58:36 -06003600 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003601 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 break;
3606 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003607 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003608 break;
3609 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003610 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 break;
3612 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003613 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 break;
3615 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003616 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003617 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003618 case glslang::EOpPackSnorm4x8:
3619 libCall = spv::GLSLstd450PackSnorm4x8;
3620 break;
3621 case glslang::EOpUnpackSnorm4x8:
3622 libCall = spv::GLSLstd450UnpackSnorm4x8;
3623 break;
3624 case glslang::EOpPackUnorm4x8:
3625 libCall = spv::GLSLstd450PackUnorm4x8;
3626 break;
3627 case glslang::EOpUnpackUnorm4x8:
3628 libCall = spv::GLSLstd450UnpackUnorm4x8;
3629 break;
3630 case glslang::EOpPackDouble2x32:
3631 libCall = spv::GLSLstd450PackDouble2x32;
3632 break;
3633 case glslang::EOpUnpackDouble2x32:
3634 libCall = spv::GLSLstd450UnpackDouble2x32;
3635 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003636
Rex Xu8ff43de2016-04-22 16:51:45 +08003637 case glslang::EOpPackInt2x32:
3638 case glslang::EOpUnpackInt2x32:
3639 case glslang::EOpPackUint2x32:
3640 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003641 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003642 break;
3643
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003644#ifdef AMD_EXTENSIONS
3645 case glslang::EOpPackFloat2x16:
3646 case glslang::EOpUnpackFloat2x16:
3647 unaryOp = spv::OpBitcast;
3648 break;
3649#endif
3650
John Kessenich140f3df2015-06-26 16:58:36 -06003651 case glslang::EOpDPdx:
3652 unaryOp = spv::OpDPdx;
3653 break;
3654 case glslang::EOpDPdy:
3655 unaryOp = spv::OpDPdy;
3656 break;
3657 case glslang::EOpFwidth:
3658 unaryOp = spv::OpFwidth;
3659 break;
3660 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003661 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003662 unaryOp = spv::OpDPdxFine;
3663 break;
3664 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003665 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003666 unaryOp = spv::OpDPdyFine;
3667 break;
3668 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003669 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003670 unaryOp = spv::OpFwidthFine;
3671 break;
3672 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003673 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003674 unaryOp = spv::OpDPdxCoarse;
3675 break;
3676 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003677 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003678 unaryOp = spv::OpDPdyCoarse;
3679 break;
3680 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003681 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003682 unaryOp = spv::OpFwidthCoarse;
3683 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003684 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003685 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003686 libCall = spv::GLSLstd450InterpolateAtCentroid;
3687 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003688 case glslang::EOpAny:
3689 unaryOp = spv::OpAny;
3690 break;
3691 case glslang::EOpAll:
3692 unaryOp = spv::OpAll;
3693 break;
3694
3695 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 if (isFloat)
3697 libCall = spv::GLSLstd450FAbs;
3698 else
3699 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 if (isFloat)
3703 libCall = spv::GLSLstd450FSign;
3704 else
3705 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707
John Kessenichfc51d282015-08-19 13:34:18 -06003708 case glslang::EOpAtomicCounterIncrement:
3709 case glslang::EOpAtomicCounterDecrement:
3710 case glslang::EOpAtomicCounter:
3711 {
3712 // Handle all of the atomics in one place, in createAtomicOperation()
3713 std::vector<spv::Id> operands;
3714 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003715 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003716 }
3717
John Kessenichfc51d282015-08-19 13:34:18 -06003718 case glslang::EOpBitFieldReverse:
3719 unaryOp = spv::OpBitReverse;
3720 break;
3721 case glslang::EOpBitCount:
3722 unaryOp = spv::OpBitCount;
3723 break;
3724 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003725 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003726 break;
3727 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003728 if (isUnsigned)
3729 libCall = spv::GLSLstd450FindUMsb;
3730 else
3731 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003732 break;
3733
Rex Xu574ab042016-04-14 16:53:07 +08003734 case glslang::EOpBallot:
3735 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003736 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003737 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003738 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003739#ifdef AMD_EXTENSIONS
3740 case glslang::EOpMinInvocations:
3741 case glslang::EOpMaxInvocations:
3742 case glslang::EOpAddInvocations:
3743 case glslang::EOpMinInvocationsNonUniform:
3744 case glslang::EOpMaxInvocationsNonUniform:
3745 case glslang::EOpAddInvocationsNonUniform:
3746#endif
Rex Xu51596642016-09-21 18:56:12 +08003747 {
3748 std::vector<spv::Id> operands;
3749 operands.push_back(operand);
3750 return createInvocationsOperation(op, typeId, operands, typeProxy);
3751 }
Rex Xu9d93a232016-05-05 12:30:44 +08003752
3753#ifdef AMD_EXTENSIONS
3754 case glslang::EOpMbcnt:
3755 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3756 libCall = spv::MbcntAMD;
3757 break;
3758
3759 case glslang::EOpCubeFaceIndex:
3760 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3761 libCall = spv::CubeFaceIndexAMD;
3762 break;
3763
3764 case glslang::EOpCubeFaceCoord:
3765 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3766 libCall = spv::CubeFaceCoordAMD;
3767 break;
3768#endif
Rex Xu338b1852016-05-05 20:38:33 +08003769
John Kessenich140f3df2015-06-26 16:58:36 -06003770 default:
3771 return 0;
3772 }
3773
3774 spv::Id id;
3775 if (libCall >= 0) {
3776 std::vector<spv::Id> args;
3777 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003778 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003779 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003780 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003781 }
John Kessenich140f3df2015-06-26 16:58:36 -06003782
qining25262b32016-05-06 17:25:16 -04003783 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003784 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003785}
3786
John Kessenich7a53f762016-01-20 11:19:27 -07003787// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003788spv::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 -07003789{
3790 // Handle unary operations vector by vector.
3791 // The result type is the same type as the original type.
3792 // The algorithm is to:
3793 // - break the matrix into vectors
3794 // - apply the operation to each vector
3795 // - make a matrix out the vector results
3796
3797 // get the types sorted out
3798 int numCols = builder.getNumColumns(operand);
3799 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003800 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3801 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003802 std::vector<spv::Id> results;
3803
3804 // do each vector op
3805 for (int c = 0; c < numCols; ++c) {
3806 std::vector<unsigned int> indexes;
3807 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003808 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3809 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3810 addDecoration(destVec, noContraction);
3811 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003812 }
3813
3814 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003815 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003816}
3817
Rex Xu73e3ce72016-04-27 18:48:17 +08003818spv::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 -06003819{
3820 spv::Op convOp = spv::OpNop;
3821 spv::Id zero = 0;
3822 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003823 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003824
3825 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3826
3827 switch (op) {
3828 case glslang::EOpConvIntToBool:
3829 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003830 case glslang::EOpConvInt64ToBool:
3831 case glslang::EOpConvUint64ToBool:
3832 zero = (op == glslang::EOpConvInt64ToBool ||
3833 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003834 zero = makeSmearedConstant(zero, vectorSize);
3835 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3836
3837 case glslang::EOpConvFloatToBool:
3838 zero = builder.makeFloatConstant(0.0F);
3839 zero = makeSmearedConstant(zero, vectorSize);
3840 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3841
3842 case glslang::EOpConvDoubleToBool:
3843 zero = builder.makeDoubleConstant(0.0);
3844 zero = makeSmearedConstant(zero, vectorSize);
3845 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3846
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003847#ifdef AMD_EXTENSIONS
3848 case glslang::EOpConvFloat16ToBool:
3849 zero = builder.makeFloat16Constant(0.0F);
3850 zero = makeSmearedConstant(zero, vectorSize);
3851 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3852#endif
3853
John Kessenich140f3df2015-06-26 16:58:36 -06003854 case glslang::EOpConvBoolToFloat:
3855 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003856 zero = builder.makeFloatConstant(0.0F);
3857 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003858 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003859
John Kessenich140f3df2015-06-26 16:58:36 -06003860 case glslang::EOpConvBoolToDouble:
3861 convOp = spv::OpSelect;
3862 zero = builder.makeDoubleConstant(0.0);
3863 one = builder.makeDoubleConstant(1.0);
3864 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003865
3866#ifdef AMD_EXTENSIONS
3867 case glslang::EOpConvBoolToFloat16:
3868 convOp = spv::OpSelect;
3869 zero = builder.makeFloat16Constant(0.0F);
3870 one = builder.makeFloat16Constant(1.0F);
3871 break;
3872#endif
3873
John Kessenich140f3df2015-06-26 16:58:36 -06003874 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003875 case glslang::EOpConvBoolToInt64:
3876 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3877 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003878 convOp = spv::OpSelect;
3879 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003880
John Kessenich140f3df2015-06-26 16:58:36 -06003881 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003882 case glslang::EOpConvBoolToUint64:
3883 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3884 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003885 convOp = spv::OpSelect;
3886 break;
3887
3888 case glslang::EOpConvIntToFloat:
3889 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003890 case glslang::EOpConvInt64ToFloat:
3891 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003892#ifdef AMD_EXTENSIONS
3893 case glslang::EOpConvIntToFloat16:
3894 case glslang::EOpConvInt64ToFloat16:
3895#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003896 convOp = spv::OpConvertSToF;
3897 break;
3898
3899 case glslang::EOpConvUintToFloat:
3900 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003901 case glslang::EOpConvUint64ToFloat:
3902 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003903#ifdef AMD_EXTENSIONS
3904 case glslang::EOpConvUintToFloat16:
3905 case glslang::EOpConvUint64ToFloat16:
3906#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003907 convOp = spv::OpConvertUToF;
3908 break;
3909
3910 case glslang::EOpConvDoubleToFloat:
3911 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003912#ifdef AMD_EXTENSIONS
3913 case glslang::EOpConvDoubleToFloat16:
3914 case glslang::EOpConvFloat16ToDouble:
3915 case glslang::EOpConvFloatToFloat16:
3916 case glslang::EOpConvFloat16ToFloat:
3917#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003918 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003919 if (builder.isMatrixType(destType))
3920 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003921 break;
3922
3923 case glslang::EOpConvFloatToInt:
3924 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003925 case glslang::EOpConvFloatToInt64:
3926 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003927#ifdef AMD_EXTENSIONS
3928 case glslang::EOpConvFloat16ToInt:
3929 case glslang::EOpConvFloat16ToInt64:
3930#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003931 convOp = spv::OpConvertFToS;
3932 break;
3933
3934 case glslang::EOpConvUintToInt:
3935 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003936 case glslang::EOpConvUint64ToInt64:
3937 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003938 if (builder.isInSpecConstCodeGenMode()) {
3939 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003940 zero = (op == glslang::EOpConvUint64ToInt64 ||
3941 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003942 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003943 // Use OpIAdd, instead of OpBitcast to do the conversion when
3944 // generating for OpSpecConstantOp instruction.
3945 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3946 }
3947 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003948 convOp = spv::OpBitcast;
3949 break;
3950
3951 case glslang::EOpConvFloatToUint:
3952 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003953 case glslang::EOpConvFloatToUint64:
3954 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003955#ifdef AMD_EXTENSIONS
3956 case glslang::EOpConvFloat16ToUint:
3957 case glslang::EOpConvFloat16ToUint64:
3958#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003959 convOp = spv::OpConvertFToU;
3960 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003961
3962 case glslang::EOpConvIntToInt64:
3963 case glslang::EOpConvInt64ToInt:
3964 convOp = spv::OpSConvert;
3965 break;
3966
3967 case glslang::EOpConvUintToUint64:
3968 case glslang::EOpConvUint64ToUint:
3969 convOp = spv::OpUConvert;
3970 break;
3971
3972 case glslang::EOpConvIntToUint64:
3973 case glslang::EOpConvInt64ToUint:
3974 case glslang::EOpConvUint64ToInt:
3975 case glslang::EOpConvUintToInt64:
3976 // OpSConvert/OpUConvert + OpBitCast
3977 switch (op) {
3978 case glslang::EOpConvIntToUint64:
3979 convOp = spv::OpSConvert;
3980 type = builder.makeIntType(64);
3981 break;
3982 case glslang::EOpConvInt64ToUint:
3983 convOp = spv::OpSConvert;
3984 type = builder.makeIntType(32);
3985 break;
3986 case glslang::EOpConvUint64ToInt:
3987 convOp = spv::OpUConvert;
3988 type = builder.makeUintType(32);
3989 break;
3990 case glslang::EOpConvUintToInt64:
3991 convOp = spv::OpUConvert;
3992 type = builder.makeUintType(64);
3993 break;
3994 default:
3995 assert(0);
3996 break;
3997 }
3998
3999 if (vectorSize > 0)
4000 type = builder.makeVectorType(type, vectorSize);
4001
4002 operand = builder.createUnaryOp(convOp, type, operand);
4003
4004 if (builder.isInSpecConstCodeGenMode()) {
4005 // Build zero scalar or vector for OpIAdd.
4006 zero = (op == glslang::EOpConvIntToUint64 ||
4007 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4008 zero = makeSmearedConstant(zero, vectorSize);
4009 // Use OpIAdd, instead of OpBitcast to do the conversion when
4010 // generating for OpSpecConstantOp instruction.
4011 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4012 }
4013 // For normal run-time conversion instruction, use OpBitcast.
4014 convOp = spv::OpBitcast;
4015 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004016 default:
4017 break;
4018 }
4019
4020 spv::Id result = 0;
4021 if (convOp == spv::OpNop)
4022 return result;
4023
4024 if (convOp == spv::OpSelect) {
4025 zero = makeSmearedConstant(zero, vectorSize);
4026 one = makeSmearedConstant(one, vectorSize);
4027 result = builder.createTriOp(convOp, destType, operand, one, zero);
4028 } else
4029 result = builder.createUnaryOp(convOp, destType, operand);
4030
John Kessenich32cfd492016-02-02 12:37:46 -07004031 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004032}
4033
4034spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4035{
4036 if (vectorSize == 0)
4037 return constant;
4038
4039 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4040 std::vector<spv::Id> components;
4041 for (int c = 0; c < vectorSize; ++c)
4042 components.push_back(constant);
4043 return builder.makeCompositeConstant(vectorTypeId, components);
4044}
4045
John Kessenich426394d2015-07-23 10:22:48 -06004046// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004047spv::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 -06004048{
4049 spv::Op opCode = spv::OpNop;
4050
4051 switch (op) {
4052 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004053 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004054 opCode = spv::OpAtomicIAdd;
4055 break;
4056 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004057 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004058 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004059 break;
4060 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004061 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004062 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004063 break;
4064 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004065 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004066 opCode = spv::OpAtomicAnd;
4067 break;
4068 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004069 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004070 opCode = spv::OpAtomicOr;
4071 break;
4072 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004073 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004074 opCode = spv::OpAtomicXor;
4075 break;
4076 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004077 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004078 opCode = spv::OpAtomicExchange;
4079 break;
4080 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004081 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004082 opCode = spv::OpAtomicCompareExchange;
4083 break;
4084 case glslang::EOpAtomicCounterIncrement:
4085 opCode = spv::OpAtomicIIncrement;
4086 break;
4087 case glslang::EOpAtomicCounterDecrement:
4088 opCode = spv::OpAtomicIDecrement;
4089 break;
4090 case glslang::EOpAtomicCounter:
4091 opCode = spv::OpAtomicLoad;
4092 break;
4093 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004094 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004095 break;
4096 }
4097
4098 // Sort out the operands
4099 // - mapping from glslang -> SPV
4100 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004101 // - compare-exchange swaps the value and comparator
4102 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004103 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4104 auto opIt = operands.begin(); // walk the glslang operands
4105 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004106 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4107 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4108 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004109 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4110 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004111 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004112 spvAtomicOperands.push_back(*(opIt + 1));
4113 spvAtomicOperands.push_back(*opIt);
4114 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004115 }
John Kessenich426394d2015-07-23 10:22:48 -06004116
John Kessenich3e60a6f2015-09-14 22:45:16 -06004117 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004118 for (; opIt != operands.end(); ++opIt)
4119 spvAtomicOperands.push_back(*opIt);
4120
4121 return builder.createOp(opCode, typeId, spvAtomicOperands);
4122}
4123
John Kessenich91cef522016-05-05 16:45:40 -06004124// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004125spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004126{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004127#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004128 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004129 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004130#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004131
Rex Xu51596642016-09-21 18:56:12 +08004132 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004133
Rex Xu51596642016-09-21 18:56:12 +08004134 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004135 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4136 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004137 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4138 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4139 } else {
4140 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004141#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004142 if (op == glslang::EOpMinInvocationsNonUniform ||
4143 op == glslang::EOpMaxInvocationsNonUniform ||
4144 op == glslang::EOpAddInvocationsNonUniform)
4145 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004146#endif
Rex Xu51596642016-09-21 18:56:12 +08004147
4148 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004149#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004150 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4151 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4152 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004153#endif
Rex Xu51596642016-09-21 18:56:12 +08004154 }
4155
4156 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4157 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004158
4159 switch (op) {
4160 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004161 opCode = spv::OpGroupAny;
4162 break;
John Kessenich91cef522016-05-05 16:45:40 -06004163 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004164 opCode = spv::OpGroupAll;
4165 break;
John Kessenich91cef522016-05-05 16:45:40 -06004166 case glslang::EOpAllInvocationsEqual:
4167 {
Rex Xu51596642016-09-21 18:56:12 +08004168 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4169 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004170
4171 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4172 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4173 }
Rex Xu51596642016-09-21 18:56:12 +08004174
4175 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004176 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004177 if (builder.isVectorType(typeId))
4178 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004179 break;
4180 case glslang::EOpReadFirstInvocation:
4181 opCode = spv::OpSubgroupFirstInvocationKHR;
4182 break;
4183 case glslang::EOpBallot:
4184 {
4185 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4186 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4187 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4188 //
4189 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4190 //
4191 spv::Id uintType = builder.makeUintType(32);
4192 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4193 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4194
4195 std::vector<spv::Id> components;
4196 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4197 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4198
4199 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4200 return builder.createUnaryOp(spv::OpBitcast, typeId,
4201 builder.createCompositeConstruct(uvec2Type, components));
4202 }
4203
Rex Xu9d93a232016-05-05 12:30:44 +08004204#ifdef AMD_EXTENSIONS
4205 case glslang::EOpMinInvocations:
4206 case glslang::EOpMaxInvocations:
4207 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004208 if (op == glslang::EOpMinInvocations) {
4209 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004210 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004211 else {
4212 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004213 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004214 else
Rex Xu51596642016-09-21 18:56:12 +08004215 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004216 }
4217 } else if (op == glslang::EOpMaxInvocations) {
4218 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004219 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004220 else {
4221 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004222 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004223 else
Rex Xu51596642016-09-21 18:56:12 +08004224 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004225 }
4226 } else {
4227 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004228 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004229 else
Rex Xu51596642016-09-21 18:56:12 +08004230 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004231 }
4232
Rex Xu2bbbe062016-08-23 15:41:05 +08004233 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004234 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004235
4236 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004237 case glslang::EOpMinInvocationsNonUniform:
4238 case glslang::EOpMaxInvocationsNonUniform:
4239 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004240 if (op == glslang::EOpMinInvocationsNonUniform) {
4241 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004242 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004243 else {
4244 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004245 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004246 else
Rex Xu51596642016-09-21 18:56:12 +08004247 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004248 }
4249 }
4250 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4251 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004252 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004253 else {
4254 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004255 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004256 else
Rex Xu51596642016-09-21 18:56:12 +08004257 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004258 }
4259 }
4260 else {
4261 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004262 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004263 else
Rex Xu51596642016-09-21 18:56:12 +08004264 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004265 }
4266
Rex Xu2bbbe062016-08-23 15:41:05 +08004267 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004268 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004269
4270 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004271#endif
John Kessenich91cef522016-05-05 16:45:40 -06004272 default:
4273 logger->missingFunctionality("invocation operation");
4274 return spv::NoResult;
4275 }
Rex Xu51596642016-09-21 18:56:12 +08004276
4277 assert(opCode != spv::OpNop);
4278 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004279}
4280
Rex Xu2bbbe062016-08-23 15:41:05 +08004281// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004282spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004283{
Rex Xub7072052016-09-26 15:53:40 +08004284#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004285 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4286 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004287 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004288 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004289 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4290 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4291 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004292#else
4293 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4294 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004295 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4296 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004297#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004298
4299 // Handle group invocation operations scalar by scalar.
4300 // The result type is the same type as the original type.
4301 // The algorithm is to:
4302 // - break the vector into scalars
4303 // - apply the operation to each scalar
4304 // - make a vector out the scalar results
4305
4306 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004307 int numComponents = builder.getNumComponents(operands[0]);
4308 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004309 std::vector<spv::Id> results;
4310
4311 // do each scalar op
4312 for (int comp = 0; comp < numComponents; ++comp) {
4313 std::vector<unsigned int> indexes;
4314 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004315 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004316 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004317 if (op == spv::OpSubgroupReadInvocationKHR) {
4318 spvGroupOperands.push_back(scalar);
4319 spvGroupOperands.push_back(operands[1]);
4320 } else if (op == spv::OpGroupBroadcast) {
4321 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004322 spvGroupOperands.push_back(scalar);
4323 spvGroupOperands.push_back(operands[1]);
4324 } else {
chaocf200da82016-12-20 12:44:35 -08004325 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004326 spvGroupOperands.push_back(spv::GroupOperationReduce);
4327 spvGroupOperands.push_back(scalar);
4328 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004329
Rex Xub7072052016-09-26 15:53:40 +08004330 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004331 }
4332
4333 // put the pieces together
4334 return builder.createCompositeConstruct(typeId, results);
4335}
Rex Xu2bbbe062016-08-23 15:41:05 +08004336
John Kessenich5e4b1242015-08-06 22:53:06 -06004337spv::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 -06004338{
Rex Xu8ff43de2016-04-22 16:51:45 +08004339 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004340#ifdef AMD_EXTENSIONS
4341 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4342#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004343 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004344#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004345
John Kessenich140f3df2015-06-26 16:58:36 -06004346 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004347 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004348 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004349 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004350 spv::Id typeId0 = 0;
4351 if (consumedOperands > 0)
4352 typeId0 = builder.getTypeId(operands[0]);
4353 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004354
4355 switch (op) {
4356 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004357 if (isFloat)
4358 libCall = spv::GLSLstd450FMin;
4359 else if (isUnsigned)
4360 libCall = spv::GLSLstd450UMin;
4361 else
4362 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004363 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004364 break;
4365 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004367 break;
4368 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004369 if (isFloat)
4370 libCall = spv::GLSLstd450FMax;
4371 else if (isUnsigned)
4372 libCall = spv::GLSLstd450UMax;
4373 else
4374 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004375 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004376 break;
4377 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004378 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004379 break;
4380 case glslang::EOpDot:
4381 opCode = spv::OpDot;
4382 break;
4383 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004384 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004385 break;
4386
4387 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004388 if (isFloat)
4389 libCall = spv::GLSLstd450FClamp;
4390 else if (isUnsigned)
4391 libCall = spv::GLSLstd450UClamp;
4392 else
4393 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004394 builder.promoteScalar(precision, operands.front(), operands[1]);
4395 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004396 break;
4397 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004398 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4399 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004400 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004401 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004402 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004403 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004404 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004405 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004406 break;
4407 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004408 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004409 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004410 break;
4411 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004412 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004413 builder.promoteScalar(precision, operands[0], operands[2]);
4414 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004415 break;
4416
4417 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004418 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004419 break;
4420 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004422 break;
4423 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004424 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004425 break;
4426 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004427 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004428 break;
4429 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004430 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004431 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004432 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004433 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004434 libCall = spv::GLSLstd450InterpolateAtSample;
4435 break;
4436 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004437 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004438 libCall = spv::GLSLstd450InterpolateAtOffset;
4439 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004440 case glslang::EOpAddCarry:
4441 opCode = spv::OpIAddCarry;
4442 typeId = builder.makeStructResultType(typeId0, typeId0);
4443 consumedOperands = 2;
4444 break;
4445 case glslang::EOpSubBorrow:
4446 opCode = spv::OpISubBorrow;
4447 typeId = builder.makeStructResultType(typeId0, typeId0);
4448 consumedOperands = 2;
4449 break;
4450 case glslang::EOpUMulExtended:
4451 opCode = spv::OpUMulExtended;
4452 typeId = builder.makeStructResultType(typeId0, typeId0);
4453 consumedOperands = 2;
4454 break;
4455 case glslang::EOpIMulExtended:
4456 opCode = spv::OpSMulExtended;
4457 typeId = builder.makeStructResultType(typeId0, typeId0);
4458 consumedOperands = 2;
4459 break;
4460 case glslang::EOpBitfieldExtract:
4461 if (isUnsigned)
4462 opCode = spv::OpBitFieldUExtract;
4463 else
4464 opCode = spv::OpBitFieldSExtract;
4465 break;
4466 case glslang::EOpBitfieldInsert:
4467 opCode = spv::OpBitFieldInsert;
4468 break;
4469
4470 case glslang::EOpFma:
4471 libCall = spv::GLSLstd450Fma;
4472 break;
4473 case glslang::EOpFrexp:
4474 libCall = spv::GLSLstd450FrexpStruct;
4475 if (builder.getNumComponents(operands[0]) == 1)
4476 frexpIntType = builder.makeIntegerType(32, true);
4477 else
4478 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4479 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4480 consumedOperands = 1;
4481 break;
4482 case glslang::EOpLdexp:
4483 libCall = spv::GLSLstd450Ldexp;
4484 break;
4485
Rex Xu574ab042016-04-14 16:53:07 +08004486 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004487 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004488
Rex Xu9d93a232016-05-05 12:30:44 +08004489#ifdef AMD_EXTENSIONS
4490 case glslang::EOpSwizzleInvocations:
4491 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4492 libCall = spv::SwizzleInvocationsAMD;
4493 break;
4494 case glslang::EOpSwizzleInvocationsMasked:
4495 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4496 libCall = spv::SwizzleInvocationsMaskedAMD;
4497 break;
4498 case glslang::EOpWriteInvocation:
4499 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4500 libCall = spv::WriteInvocationAMD;
4501 break;
4502
4503 case glslang::EOpMin3:
4504 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4505 if (isFloat)
4506 libCall = spv::FMin3AMD;
4507 else {
4508 if (isUnsigned)
4509 libCall = spv::UMin3AMD;
4510 else
4511 libCall = spv::SMin3AMD;
4512 }
4513 break;
4514 case glslang::EOpMax3:
4515 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4516 if (isFloat)
4517 libCall = spv::FMax3AMD;
4518 else {
4519 if (isUnsigned)
4520 libCall = spv::UMax3AMD;
4521 else
4522 libCall = spv::SMax3AMD;
4523 }
4524 break;
4525 case glslang::EOpMid3:
4526 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4527 if (isFloat)
4528 libCall = spv::FMid3AMD;
4529 else {
4530 if (isUnsigned)
4531 libCall = spv::UMid3AMD;
4532 else
4533 libCall = spv::SMid3AMD;
4534 }
4535 break;
4536
4537 case glslang::EOpInterpolateAtVertex:
4538 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4539 libCall = spv::InterpolateAtVertexAMD;
4540 break;
4541#endif
4542
John Kessenich140f3df2015-06-26 16:58:36 -06004543 default:
4544 return 0;
4545 }
4546
4547 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004548 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004549 // Use an extended instruction from the standard library.
4550 // Construct the call arguments, without modifying the original operands vector.
4551 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4552 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004553 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004554 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004555 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004556 case 0:
4557 // should all be handled by visitAggregate and createNoArgOperation
4558 assert(0);
4559 return 0;
4560 case 1:
4561 // should all be handled by createUnaryOperation
4562 assert(0);
4563 return 0;
4564 case 2:
4565 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4566 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004567 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004568 // anything 3 or over doesn't have l-value operands, so all should be consumed
4569 assert(consumedOperands == operands.size());
4570 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004571 break;
4572 }
4573 }
4574
John Kessenich55e7d112015-11-15 21:33:39 -07004575 // Decode the return types that were structures
4576 switch (op) {
4577 case glslang::EOpAddCarry:
4578 case glslang::EOpSubBorrow:
4579 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4580 id = builder.createCompositeExtract(id, typeId0, 0);
4581 break;
4582 case glslang::EOpUMulExtended:
4583 case glslang::EOpIMulExtended:
4584 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4585 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4586 break;
4587 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004588 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004589 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4590 id = builder.createCompositeExtract(id, typeId0, 0);
4591 break;
4592 default:
4593 break;
4594 }
4595
John Kessenich32cfd492016-02-02 12:37:46 -07004596 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004597}
4598
Rex Xu9d93a232016-05-05 12:30:44 +08004599// Intrinsics with no arguments (or no return value, and no precision).
4600spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004601{
4602 // TODO: get the barrier operands correct
4603
4604 switch (op) {
4605 case glslang::EOpEmitVertex:
4606 builder.createNoResultOp(spv::OpEmitVertex);
4607 return 0;
4608 case glslang::EOpEndPrimitive:
4609 builder.createNoResultOp(spv::OpEndPrimitive);
4610 return 0;
4611 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004612 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 return 0;
4614 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004616 return 0;
4617 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004618 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004619 return 0;
4620 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004621 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004622 return 0;
4623 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004624 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004625 return 0;
4626 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004627 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004628 return 0;
4629 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004630 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004631 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004632 case glslang::EOpAllMemoryBarrierWithGroupSync:
4633 // Control barrier with non-"None" semantic is also a memory barrier.
4634 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4635 return 0;
4636 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4637 // Control barrier with non-"None" semantic is also a memory barrier.
4638 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4639 return 0;
4640 case glslang::EOpWorkgroupMemoryBarrier:
4641 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4642 return 0;
4643 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4644 // Control barrier with non-"None" semantic is also a memory barrier.
4645 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4646 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004647#ifdef AMD_EXTENSIONS
4648 case glslang::EOpTime:
4649 {
4650 std::vector<spv::Id> args; // Dummy arguments
4651 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4652 return builder.setPrecision(id, precision);
4653 }
4654#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004655 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004656 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004657 return 0;
4658 }
4659}
4660
4661spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4662{
John Kessenich2f273362015-07-18 22:34:27 -06004663 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004664 spv::Id id;
4665 if (symbolValues.end() != iter) {
4666 id = iter->second;
4667 return id;
4668 }
4669
4670 // it was not found, create it
4671 id = createSpvVariable(symbol);
4672 symbolValues[symbol->getId()] = id;
4673
Rex Xuc884b4a2016-06-29 15:03:44 +08004674 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004675 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004676 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004677 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004678 if (symbol->getType().getQualifier().hasSpecConstantId())
4679 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004680 if (symbol->getQualifier().hasIndex())
4681 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4682 if (symbol->getQualifier().hasComponent())
4683 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4684 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004685 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004686 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004687 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004688 if (symbol->getQualifier().hasXfbBuffer())
4689 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4690 if (symbol->getQualifier().hasXfbOffset())
4691 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4692 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004693 // atomic counters use this:
4694 if (symbol->getQualifier().hasOffset())
4695 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004696 }
4697
scygan2c864272016-05-18 18:09:17 +02004698 if (symbol->getQualifier().hasLocation())
4699 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004700 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004701 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004702 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004703 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004704 }
John Kessenich140f3df2015-06-26 16:58:36 -06004705 if (symbol->getQualifier().hasSet())
4706 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004707 else if (IsDescriptorResource(symbol->getType())) {
4708 // default to 0
4709 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4710 }
John Kessenich140f3df2015-06-26 16:58:36 -06004711 if (symbol->getQualifier().hasBinding())
4712 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004713 if (symbol->getQualifier().hasAttachment())
4714 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004715 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004716 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004717 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004718 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004719 if (symbol->getQualifier().hasXfbBuffer())
4720 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4721 }
4722
Rex Xu1da878f2016-02-21 20:59:01 +08004723 if (symbol->getType().isImage()) {
4724 std::vector<spv::Decoration> memory;
4725 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4726 for (unsigned int i = 0; i < memory.size(); ++i)
4727 addDecoration(id, memory[i]);
4728 }
4729
John Kessenich140f3df2015-06-26 16:58:36 -06004730 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004731 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004732 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004733 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004734
John Kessenichecba76f2017-01-06 00:34:48 -07004735#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004736 if (builtIn == spv::BuiltInSampleMask) {
4737 spv::Decoration decoration;
4738 // GL_NV_sample_mask_override_coverage extension
4739 if (glslangIntermediate->getLayoutOverrideCoverage())
4740 decoration = (spv::Decoration)spv::OverrideCoverageNV;
4741 else
4742 decoration = (spv::Decoration)spv::DecorationMax;
4743 addDecoration(id, decoration);
4744 if (decoration != spv::DecorationMax) {
4745 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4746 }
4747 }
chaoc6e5acae2016-12-20 13:28:52 -08004748 if (symbol->getQualifier().layoutPassthrough) {
4749 addDecoration(id, spv::PassthroughNV);
4750 builder.addCapability(spv::GeometryShaderPassthroughNV);
4751 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4752 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004753#endif
4754
John Kessenich140f3df2015-06-26 16:58:36 -06004755 return id;
4756}
4757
John Kessenich55e7d112015-11-15 21:33:39 -07004758// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004759void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4760{
John Kessenich4016e382016-07-15 11:53:56 -06004761 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004762 builder.addDecoration(id, dec);
4763}
4764
John Kessenich55e7d112015-11-15 21:33:39 -07004765// If 'dec' is valid, add a one-operand decoration to an object
4766void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4767{
John Kessenich4016e382016-07-15 11:53:56 -06004768 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004769 builder.addDecoration(id, dec, value);
4770}
4771
4772// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004773void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4774{
John Kessenich4016e382016-07-15 11:53:56 -06004775 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004776 builder.addMemberDecoration(id, (unsigned)member, dec);
4777}
4778
John Kessenich92187592016-02-01 13:45:25 -07004779// If 'dec' is valid, add a one-operand decoration to a struct member
4780void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4781{
John Kessenich4016e382016-07-15 11:53:56 -06004782 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004783 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4784}
4785
John Kessenich55e7d112015-11-15 21:33:39 -07004786// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004787// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004788//
4789// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4790//
4791// Recursively walk the nodes. The nodes form a tree whose leaves are
4792// regular constants, which themselves are trees that createSpvConstant()
4793// recursively walks. So, this function walks the "top" of the tree:
4794// - emit specialization constant-building instructions for specConstant
4795// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004796spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004797{
John Kessenich7cc0e282016-03-20 00:46:02 -06004798 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004799
qining4f4bb812016-04-03 23:55:17 -04004800 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004801 if (! node.getQualifier().specConstant) {
4802 // hand off to the non-spec-constant path
4803 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4804 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004805 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004806 nextConst, false);
4807 }
4808
4809 // We now know we have a specialization constant to build
4810
John Kessenichd94c0032016-05-30 19:29:40 -06004811 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004812 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4813 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4814 std::vector<spv::Id> dimConstId;
4815 for (int dim = 0; dim < 3; ++dim) {
4816 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4817 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4818 if (specConst)
4819 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4820 }
4821 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4822 }
4823
4824 // An AST node labelled as specialization constant should be a symbol node.
4825 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4826 if (auto* sn = node.getAsSymbolNode()) {
4827 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004828 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4829 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4830 // will set the builder into spec constant op instruction generating mode.
4831 sub_tree->traverse(this);
4832 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004833 } else if (auto* const_union_array = &sn->getConstArray()){
4834 int nextConst = 0;
4835 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004836 }
4837 }
qining4f4bb812016-04-03 23:55:17 -04004838
4839 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4840 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004841 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004842 exit(1);
4843 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004844}
4845
John Kessenich140f3df2015-06-26 16:58:36 -06004846// Use 'consts' as the flattened glslang source of scalar constants to recursively
4847// build the aggregate SPIR-V constant.
4848//
4849// If there are not enough elements present in 'consts', 0 will be substituted;
4850// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4851//
qining08408382016-03-21 09:51:37 -04004852spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004853{
4854 // vector of constants for SPIR-V
4855 std::vector<spv::Id> spvConsts;
4856
4857 // Type is used for struct and array constants
4858 spv::Id typeId = convertGlslangToSpvType(glslangType);
4859
4860 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004861 glslang::TType elementType(glslangType, 0);
4862 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004863 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004864 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004865 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004866 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004867 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004868 } else if (glslangType.getStruct()) {
4869 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4870 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004871 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004872 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004873 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4874 bool zero = nextConst >= consts.size();
4875 switch (glslangType.getBasicType()) {
4876 case glslang::EbtInt:
4877 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4878 break;
4879 case glslang::EbtUint:
4880 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4881 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004882 case glslang::EbtInt64:
4883 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4884 break;
4885 case glslang::EbtUint64:
4886 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4887 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004888 case glslang::EbtFloat:
4889 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4890 break;
4891 case glslang::EbtDouble:
4892 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4893 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004894#ifdef AMD_EXTENSIONS
4895 case glslang::EbtFloat16:
4896 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4897 break;
4898#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004899 case glslang::EbtBool:
4900 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4901 break;
4902 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004903 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004904 break;
4905 }
4906 ++nextConst;
4907 }
4908 } else {
4909 // we have a non-aggregate (scalar) constant
4910 bool zero = nextConst >= consts.size();
4911 spv::Id scalar = 0;
4912 switch (glslangType.getBasicType()) {
4913 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004914 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004915 break;
4916 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004917 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004918 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004919 case glslang::EbtInt64:
4920 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4921 break;
4922 case glslang::EbtUint64:
4923 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4924 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004925 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004926 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004927 break;
4928 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004929 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004930 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004931#ifdef AMD_EXTENSIONS
4932 case glslang::EbtFloat16:
4933 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4934 break;
4935#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004936 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004937 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004938 break;
4939 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004940 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004941 break;
4942 }
4943 ++nextConst;
4944 return scalar;
4945 }
4946
4947 return builder.makeCompositeConstant(typeId, spvConsts);
4948}
4949
John Kessenich7c1aa102015-10-15 13:29:11 -06004950// Return true if the node is a constant or symbol whose reading has no
4951// non-trivial observable cost or effect.
4952bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4953{
4954 // don't know what this is
4955 if (node == nullptr)
4956 return false;
4957
4958 // a constant is safe
4959 if (node->getAsConstantUnion() != nullptr)
4960 return true;
4961
4962 // not a symbol means non-trivial
4963 if (node->getAsSymbolNode() == nullptr)
4964 return false;
4965
4966 // a symbol, depends on what's being read
4967 switch (node->getType().getQualifier().storage) {
4968 case glslang::EvqTemporary:
4969 case glslang::EvqGlobal:
4970 case glslang::EvqIn:
4971 case glslang::EvqInOut:
4972 case glslang::EvqConst:
4973 case glslang::EvqConstReadOnly:
4974 case glslang::EvqUniform:
4975 return true;
4976 default:
4977 return false;
4978 }
qining25262b32016-05-06 17:25:16 -04004979}
John Kessenich7c1aa102015-10-15 13:29:11 -06004980
4981// A node is trivial if it is a single operation with no side effects.
4982// Error on the side of saying non-trivial.
4983// Return true if trivial.
4984bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4985{
4986 if (node == nullptr)
4987 return false;
4988
4989 // symbols and constants are trivial
4990 if (isTrivialLeaf(node))
4991 return true;
4992
4993 // otherwise, it needs to be a simple operation or one or two leaf nodes
4994
4995 // not a simple operation
4996 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4997 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4998 if (binaryNode == nullptr && unaryNode == nullptr)
4999 return false;
5000
5001 // not on leaf nodes
5002 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5003 return false;
5004
5005 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5006 return false;
5007 }
5008
5009 switch (node->getAsOperator()->getOp()) {
5010 case glslang::EOpLogicalNot:
5011 case glslang::EOpConvIntToBool:
5012 case glslang::EOpConvUintToBool:
5013 case glslang::EOpConvFloatToBool:
5014 case glslang::EOpConvDoubleToBool:
5015 case glslang::EOpEqual:
5016 case glslang::EOpNotEqual:
5017 case glslang::EOpLessThan:
5018 case glslang::EOpGreaterThan:
5019 case glslang::EOpLessThanEqual:
5020 case glslang::EOpGreaterThanEqual:
5021 case glslang::EOpIndexDirect:
5022 case glslang::EOpIndexDirectStruct:
5023 case glslang::EOpLogicalXor:
5024 case glslang::EOpAny:
5025 case glslang::EOpAll:
5026 return true;
5027 default:
5028 return false;
5029 }
5030}
5031
5032// Emit short-circuiting code, where 'right' is never evaluated unless
5033// the left side is true (for &&) or false (for ||).
5034spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5035{
5036 spv::Id boolTypeId = builder.makeBoolType();
5037
5038 // emit left operand
5039 builder.clearAccessChain();
5040 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005041 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005042
5043 // Operands to accumulate OpPhi operands
5044 std::vector<spv::Id> phiOperands;
5045 // accumulate left operand's phi information
5046 phiOperands.push_back(leftId);
5047 phiOperands.push_back(builder.getBuildPoint()->getId());
5048
5049 // Make the two kinds of operation symmetric with a "!"
5050 // || => emit "if (! left) result = right"
5051 // && => emit "if ( left) result = right"
5052 //
5053 // TODO: this runtime "not" for || could be avoided by adding functionality
5054 // to 'builder' to have an "else" without an "then"
5055 if (op == glslang::EOpLogicalOr)
5056 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5057
5058 // make an "if" based on the left value
5059 spv::Builder::If ifBuilder(leftId, builder);
5060
5061 // emit right operand as the "then" part of the "if"
5062 builder.clearAccessChain();
5063 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005064 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005065
5066 // accumulate left operand's phi information
5067 phiOperands.push_back(rightId);
5068 phiOperands.push_back(builder.getBuildPoint()->getId());
5069
5070 // finish the "if"
5071 ifBuilder.makeEndIf();
5072
5073 // phi together the two results
5074 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5075}
5076
Rex Xu9d93a232016-05-05 12:30:44 +08005077// Return type Id of the imported set of extended instructions corresponds to the name.
5078// Import this set if it has not been imported yet.
5079spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5080{
5081 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5082 return extBuiltinMap[name];
5083 else {
Rex Xu51596642016-09-21 18:56:12 +08005084 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005085 spv::Id extBuiltins = builder.import(name);
5086 extBuiltinMap[name] = extBuiltins;
5087 return extBuiltins;
5088 }
5089}
5090
John Kessenich140f3df2015-06-26 16:58:36 -06005091}; // end anonymous namespace
5092
5093namespace glslang {
5094
John Kessenich68d78fd2015-07-12 19:28:10 -06005095void GetSpirvVersion(std::string& version)
5096{
John Kessenich9e55f632015-07-15 10:03:39 -06005097 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005098 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005099 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005100 version = buf;
5101}
5102
John Kessenich140f3df2015-06-26 16:58:36 -06005103// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005104void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005105{
5106 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005107 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005108 for (int i = 0; i < (int)spirv.size(); ++i) {
5109 unsigned int word = spirv[i];
5110 out.write((const char*)&word, 4);
5111 }
5112 out.close();
5113}
5114
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005115// Write SPIR-V out to a text file with 32-bit hexadecimal words
5116void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5117{
5118 std::ofstream out;
5119 out.open(baseName, std::ios::binary | std::ios::out);
5120 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5121 const int WORDS_PER_LINE = 8;
5122 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5123 out << "\t";
5124 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5125 const unsigned int word = spirv[i + j];
5126 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5127 if (i + j + 1 < (int)spirv.size()) {
5128 out << ",";
5129 }
5130 }
5131 out << std::endl;
5132 }
5133 out.close();
5134}
5135
John Kessenich140f3df2015-06-26 16:58:36 -06005136//
5137// Set up the glslang traversal
5138//
5139void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5140{
Lei Zhang17535f72016-05-04 15:55:59 -04005141 spv::SpvBuildLogger logger;
5142 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005143}
5144
Lei Zhang17535f72016-05-04 15:55:59 -04005145void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005146{
John Kessenich140f3df2015-06-26 16:58:36 -06005147 TIntermNode* root = intermediate.getTreeRoot();
5148
5149 if (root == 0)
5150 return;
5151
5152 glslang::GetThreadPoolAllocator().push();
5153
Lei Zhang17535f72016-05-04 15:55:59 -04005154 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005155 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005156 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005157 it.dumpSpv(spirv);
5158
5159 glslang::GetThreadPoolAllocator().pop();
5160}
5161
5162}; // end namespace glslang