blob: bf26cdcf9c827b8da6309ac851ead47ae6c083f7 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600132 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
133 glslang::TLayoutPacking, const glslang::TQualifier&);
134 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
135 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700136 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700137 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800138 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600139 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700140 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700141 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
142 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100144 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600145
John Kessenich6fccb3c2016-09-19 16:01:41 -0600146 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 void makeFunctions(const glslang::TIntermSequence&);
148 void makeGlobalInitializers(const glslang::TIntermSequence&);
149 void visitFunctions(const glslang::TIntermSequence&);
150 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800151 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600152 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
153 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
155
qining25262b32016-05-06 17:25:16 -0400156 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
157 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
158 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800159 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800160 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800163 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600165 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800166 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
168 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700169 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400172 spv::Id createSpvConstant(const glslang::TIntermTyped&);
173 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600174 bool isTrivialLeaf(const glslang::TIntermTyped* node);
175 bool isTrivial(const glslang::TIntermTyped* node);
176 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800177 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600178
179 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600180 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700181 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600182 int sequenceDepth;
183
Lei Zhang17535f72016-05-04 15:55:59 -0400184 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400185
John Kessenich140f3df2015-06-26 16:58:36 -0600186 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
187 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700188 bool inEntryPoint;
189 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700190 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700191 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600192 const glslang::TIntermediate* glslangIntermediate;
193 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800194 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600195
John Kessenich2f273362015-07-18 22:34:27 -0600196 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600197 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600198 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700199 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600200 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600201 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600202};
203
204//
205// Helper functions for translating glslang representations to SPIR-V enumerants.
206//
207
208// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700209spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600210{
John Kessenich66e2faf2016-03-12 18:34:36 -0700211 switch (source) {
212 case glslang::EShSourceGlsl:
213 switch (profile) {
214 case ENoProfile:
215 case ECoreProfile:
216 case ECompatibilityProfile:
217 return spv::SourceLanguageGLSL;
218 case EEsProfile:
219 return spv::SourceLanguageESSL;
220 default:
221 return spv::SourceLanguageUnknown;
222 }
223 case glslang::EShSourceHlsl:
John Kessenich927608b2017-01-06 12:34:14 -0700224 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400225 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtSampler)
255 return spv::StorageClassUniformConstant;
256 else if (type.getBasicType() == glslang::EbtAtomicUint)
257 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600265 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600266 } else {
267 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700268 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
269 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
271 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::StorageClassFunction;
275 }
276 }
277}
278
279// Translate glslang sampler type to SPIR-V dimensionality.
280spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
281{
282 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700283 case glslang::Esd1D: return spv::Dim1D;
284 case glslang::Esd2D: return spv::Dim2D;
285 case glslang::Esd3D: return spv::Dim3D;
286 case glslang::EsdCube: return spv::DimCube;
287 case glslang::EsdRect: return spv::DimRect;
288 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700289 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::Dim2D;
293 }
294}
295
John Kessenichf6640762016-08-01 19:44:00 -0600296// Translate glslang precision to SPIR-V precision decorations.
297spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
John Kessenichf6640762016-08-01 19:44:00 -0600299 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700300 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600301 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::NoPrecision;
304 }
305}
306
John Kessenichf6640762016-08-01 19:44:00 -0600307// Translate glslang type to SPIR-V precision decorations.
308spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
309{
310 return TranslatePrecisionDecoration(type.getQualifier().precision);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V block decorations.
314spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
315{
316 if (type.getBasicType() == glslang::EbtBlock) {
317 switch (type.getQualifier().storage) {
318 case glslang::EvqUniform: return spv::DecorationBlock;
319 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
320 case glslang::EvqVaryingIn: return spv::DecorationBlock;
321 case glslang::EvqVaryingOut: return spv::DecorationBlock;
322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 break;
325 }
326 }
327
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329}
330
Rex Xu1da878f2016-02-21 20:59:01 +0800331// Translate glslang type to SPIR-V memory decorations.
332void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
333{
334 if (qualifier.coherent)
335 memory.push_back(spv::DecorationCoherent);
336 if (qualifier.volatil)
337 memory.push_back(spv::DecorationVolatile);
338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
David Netoa901ffe2016-06-08 14:11:40 +0100442// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
443// associated capabilities when required. For some built-in variables, a capability
444// is generated only when using the variable in an executable instruction, but not when
445// just declaring a struct member variable with it. This is true for PointSize,
446// ClipDistance, and CullDistance.
447spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600448{
449 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700450 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600451 // Defer adding the capability until the built-in is actually used.
452 if (! memberDeclaration) {
453 switch (glslangIntermediate->getStage()) {
454 case EShLangGeometry:
455 builder.addCapability(spv::CapabilityGeometryPointSize);
456 break;
457 case EShLangTessControl:
458 case EShLangTessEvaluation:
459 builder.addCapability(spv::CapabilityTessellationPointSize);
460 break;
461 default:
462 break;
463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 }
465 return spv::BuiltInPointSize;
466
John Kessenichebb50532016-05-16 19:22:05 -0600467 // These *Distance capabilities logically belong here, but if the member is declared and
468 // then never used, consumers of SPIR-V prefer the capability not be declared.
469 // They are now generated when used, rather than here when declared.
470 // Potentially, the specification should be more clear what the minimum
471 // use needed is to trigger the capability.
472 //
John Kessenich92187592016-02-01 13:45:25 -0700473 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100474 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600475 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInClipDistance;
477
478 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600480 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInCullDistance;
482
483 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500484 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation)
489 {
490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
493#endif
John Kessenich92187592016-02-01 13:45:25 -0700494 return spv::BuiltInViewportIndex;
495
John Kessenich5e801132016-02-15 11:09:46 -0700496 case glslang::EbvSampleId:
497 builder.addCapability(spv::CapabilitySampleRateShading);
498 return spv::BuiltInSampleId;
499
500 case glslang::EbvSamplePosition:
501 builder.addCapability(spv::CapabilitySampleRateShading);
502 return spv::BuiltInSamplePosition;
503
504 case glslang::EbvSampleMask:
505 builder.addCapability(spv::CapabilitySampleRateShading);
506 return spv::BuiltInSampleMask;
507
John Kessenich78a45572016-07-08 14:05:15 -0600508 case glslang::EbvLayer:
509 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800510#ifdef NV_EXTENSIONS
511 if (!memberDeclaration)
512 {
513 if (glslangIntermediate->getStage() == EShLangVertex ||
514 glslangIntermediate->getStage() == EShLangTessControl ||
515 glslangIntermediate->getStage() == EShLangTessEvaluation)
516 {
517 builder.addExtension(spv::E_SPV_NV_viewport_array2);
518 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
519 }
520 }
521#endif
John Kessenich78a45572016-07-08 14:05:15 -0600522 return spv::BuiltInLayer;
523
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvVertexId: return spv::BuiltInVertexId;
526 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700527 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
528 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800529
John Kessenichda581a22015-10-14 14:10:30 -0600530 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800531 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
532 builder.addCapability(spv::CapabilityDrawParameters);
533 return spv::BuiltInBaseVertex;
534
John Kessenichda581a22015-10-14 14:10:30 -0600535 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800536 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
537 builder.addCapability(spv::CapabilityDrawParameters);
538 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200539
John Kessenichda581a22015-10-14 14:10:30 -0600540 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800541 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
542 builder.addCapability(spv::CapabilityDrawParameters);
543 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200544
545 case glslang::EbvPrimitiveId:
546 if (glslangIntermediate->getStage() == EShLangFragment)
547 builder.addCapability(spv::CapabilityGeometry);
548 return spv::BuiltInPrimitiveId;
549
John Kessenich140f3df2015-06-26 16:58:36 -0600550 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
552 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
553 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
554 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
555 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
556 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
557 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600558 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
559 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
560 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
561 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
562 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
563 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
564 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
565 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupSize;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLocalInvocationId;
576
Rex Xu574ab042016-04-14 16:53:07 +0800577 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
579 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
580 return spv::BuiltInSubgroupEqMaskKHR;
581
Rex Xu574ab042016-04-14 16:53:07 +0800582 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800583 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
584 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
585 return spv::BuiltInSubgroupGeMaskKHR;
586
Rex Xu574ab042016-04-14 16:53:07 +0800587 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800588 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
589 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
590 return spv::BuiltInSubgroupGtMaskKHR;
591
Rex Xu574ab042016-04-14 16:53:07 +0800592 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800593 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
594 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
595 return spv::BuiltInSubgroupLeMaskKHR;
596
Rex Xu574ab042016-04-14 16:53:07 +0800597 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800598 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
599 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
600 return spv::BuiltInSubgroupLtMaskKHR;
601
Rex Xu9d93a232016-05-05 12:30:44 +0800602#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800603 case glslang::EbvBaryCoordNoPersp:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordNoPerspAMD;
606
607 case glslang::EbvBaryCoordNoPerspCentroid:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
610
611 case glslang::EbvBaryCoordNoPerspSample:
612 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
613 return spv::BuiltInBaryCoordNoPerspSampleAMD;
614
615 case glslang::EbvBaryCoordSmooth:
616 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
617 return spv::BuiltInBaryCoordSmoothAMD;
618
619 case glslang::EbvBaryCoordSmoothCentroid:
620 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
621 return spv::BuiltInBaryCoordSmoothCentroidAMD;
622
623 case glslang::EbvBaryCoordSmoothSample:
624 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
625 return spv::BuiltInBaryCoordSmoothSampleAMD;
626
627 case glslang::EbvBaryCoordPullModel:
628 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
629 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800630#endif
chaoc771d89f2017-01-13 01:10:53 -0800631
632#ifdef NV_EXTENSIONS
633 case glslang::EbvViewportMaskNV:
634 builder.addExtension(spv::E_SPV_NV_viewport_array2);
635 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
636 return spv::BuiltInViewportMaskNV;
637 case glslang::EbvSecondaryPositionNV:
638 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
640 return spv::BuiltInSecondaryPositionNV;
641 case glslang::EbvSecondaryViewportMaskNV:
642 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
643 builder.addCapability(spv::CapabilityShaderStereoViewNV);
644 return spv::BuiltInSecondaryViewportMaskNV;
645#endif
John Kessenich4016e382016-07-15 11:53:56 -0600646 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600647 }
648}
649
Rex Xufc618912015-09-09 16:42:49 +0800650// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700651spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800652{
653 assert(type.getBasicType() == glslang::EbtSampler);
654
John Kessenich5d0fa972016-02-15 11:57:00 -0700655 // Check for capabilities
656 switch (type.getQualifier().layoutFormat) {
657 case glslang::ElfRg32f:
658 case glslang::ElfRg16f:
659 case glslang::ElfR11fG11fB10f:
660 case glslang::ElfR16f:
661 case glslang::ElfRgba16:
662 case glslang::ElfRgb10A2:
663 case glslang::ElfRg16:
664 case glslang::ElfRg8:
665 case glslang::ElfR16:
666 case glslang::ElfR8:
667 case glslang::ElfRgba16Snorm:
668 case glslang::ElfRg16Snorm:
669 case glslang::ElfRg8Snorm:
670 case glslang::ElfR16Snorm:
671 case glslang::ElfR8Snorm:
672
673 case glslang::ElfRg32i:
674 case glslang::ElfRg16i:
675 case glslang::ElfRg8i:
676 case glslang::ElfR16i:
677 case glslang::ElfR8i:
678
679 case glslang::ElfRgb10a2ui:
680 case glslang::ElfRg32ui:
681 case glslang::ElfRg16ui:
682 case glslang::ElfRg8ui:
683 case glslang::ElfR16ui:
684 case glslang::ElfR8ui:
685 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
686 break;
687
688 default:
689 break;
690 }
691
692 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800693 switch (type.getQualifier().layoutFormat) {
694 case glslang::ElfNone: return spv::ImageFormatUnknown;
695 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
696 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
697 case glslang::ElfR32f: return spv::ImageFormatR32f;
698 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
699 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
700 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
701 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
702 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
703 case glslang::ElfR16f: return spv::ImageFormatR16f;
704 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
705 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
706 case glslang::ElfRg16: return spv::ImageFormatRg16;
707 case glslang::ElfRg8: return spv::ImageFormatRg8;
708 case glslang::ElfR16: return spv::ImageFormatR16;
709 case glslang::ElfR8: return spv::ImageFormatR8;
710 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
711 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
712 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
713 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
714 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
715 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
716 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
717 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
718 case glslang::ElfR32i: return spv::ImageFormatR32i;
719 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
720 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
721 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
722 case glslang::ElfR16i: return spv::ImageFormatR16i;
723 case glslang::ElfR8i: return spv::ImageFormatR8i;
724 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
725 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
726 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
727 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
728 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
729 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
730 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
731 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
732 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
733 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600734 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800735 }
736}
737
qining25262b32016-05-06 17:25:16 -0400738// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700739// descriptor set.
740bool IsDescriptorResource(const glslang::TType& type)
741{
John Kessenichf7497e22016-03-08 21:36:22 -0700742 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700743 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700744 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700745
746 // non block...
747 // basically samplerXXX/subpass/sampler/texture are all included
748 // if they are the global-scope-class, not the function parameter
749 // (or local, if they ever exist) class.
750 if (type.getBasicType() == glslang::EbtSampler)
751 return type.getQualifier().isUniformOrBuffer();
752
753 // None of the above.
754 return false;
755}
756
John Kesseniche0b6cad2015-12-24 10:30:13 -0700757void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
758{
759 if (child.layoutMatrix == glslang::ElmNone)
760 child.layoutMatrix = parent.layoutMatrix;
761
762 if (parent.invariant)
763 child.invariant = true;
764 if (parent.nopersp)
765 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800766#ifdef AMD_EXTENSIONS
767 if (parent.explicitInterp)
768 child.explicitInterp = true;
769#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700770 if (parent.flat)
771 child.flat = true;
772 if (parent.centroid)
773 child.centroid = true;
774 if (parent.patch)
775 child.patch = true;
776 if (parent.sample)
777 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800778 if (parent.coherent)
779 child.coherent = true;
780 if (parent.volatil)
781 child.volatil = true;
782 if (parent.restrict)
783 child.restrict = true;
784 if (parent.readonly)
785 child.readonly = true;
786 if (parent.writeonly)
787 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700788}
789
John Kessenichf2b7f332016-09-01 17:05:23 -0600790bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700791{
John Kessenich7b9fa252016-01-21 18:56:57 -0700792 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600793 // - struct members might inherit from a struct declaration
794 // (note that non-block structs don't explicitly inherit,
795 // only implicitly, meaning no decoration involved)
796 // - affect decorations on the struct members
797 // (note smooth does not, and expecting something like volatile
798 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700799 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600800 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700801}
802
John Kessenich140f3df2015-06-26 16:58:36 -0600803//
804// Implement the TGlslangToSpvTraverser class.
805//
806
Lei Zhang17535f72016-05-04 15:55:59 -0400807TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600808 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
809 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400810 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700811 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600812 glslangIntermediate(glslangIntermediate)
813{
814 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
815
816 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700817 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600818 stdBuiltins = builder.import("GLSL.std.450");
819 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600820 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
821 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600822
823 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600824 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
825 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600826 builder.addSourceExtension(it->c_str());
827
828 // Add the top-level modes for this shader.
829
John Kessenich92187592016-02-01 13:45:25 -0700830 if (glslangIntermediate->getXfbMode()) {
831 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600832 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700833 }
John Kessenich140f3df2015-06-26 16:58:36 -0600834
835 unsigned int mode;
836 switch (glslangIntermediate->getStage()) {
837 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600838 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600839 break;
840
841 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600842 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600843 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
844 break;
845
846 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600847 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600848 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700849 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
850 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
851 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600852 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600853 }
John Kessenich4016e382016-07-15 11:53:56 -0600854 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600855 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
856
John Kesseniche6903322015-10-13 16:29:02 -0600857 switch (glslangIntermediate->getVertexSpacing()) {
858 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
859 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
860 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600861 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600862 }
John Kessenich4016e382016-07-15 11:53:56 -0600863 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600864 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
865
866 switch (glslangIntermediate->getVertexOrder()) {
867 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
868 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600869 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600870 }
John Kessenich4016e382016-07-15 11:53:56 -0600871 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600872 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
873
874 if (glslangIntermediate->getPointMode())
875 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600876 break;
877
878 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600879 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600880 switch (glslangIntermediate->getInputPrimitive()) {
881 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
882 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
883 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700884 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600885 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600886 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600887 }
John Kessenich4016e382016-07-15 11:53:56 -0600888 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600889 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600890
John Kessenich140f3df2015-06-26 16:58:36 -0600891 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
892
893 switch (glslangIntermediate->getOutputPrimitive()) {
894 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
895 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
896 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600897 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600898 }
John Kessenich4016e382016-07-15 11:53:56 -0600899 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600900 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
901 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
902 break;
903
904 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600905 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600906 if (glslangIntermediate->getPixelCenterInteger())
907 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600908
John Kessenich140f3df2015-06-26 16:58:36 -0600909 if (glslangIntermediate->getOriginUpperLeft())
910 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600911 else
912 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600913
914 if (glslangIntermediate->getEarlyFragmentTests())
915 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
916
917 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600918 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
919 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600920 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600921 }
John Kessenich4016e382016-07-15 11:53:56 -0600922 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600923 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
924
925 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
926 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600927 break;
928
929 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600930 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600931 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
932 glslangIntermediate->getLocalSize(1),
933 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600934 break;
935
936 default:
937 break;
938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939}
940
John Kessenichfca82622016-11-26 13:23:20 -0700941// Finish creating SPV, after the traversal is complete.
942void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700943{
John Kessenich517fe7a2016-11-26 13:31:47 -0700944 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700945 builder.setBuildPoint(shaderEntry->getLastBlock());
946 builder.leaveFunction();
947 }
948
John Kessenich7ba63412015-12-20 17:37:07 -0700949 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100950 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
951 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700952
qiningda397332016-03-09 19:54:03 -0500953 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700954}
955
John Kessenichfca82622016-11-26 13:23:20 -0700956// Write the SPV into 'out'.
957void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600958{
John Kessenichfca82622016-11-26 13:23:20 -0700959 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600960}
961
962//
963// Implement the traversal functions.
964//
965// Return true from interior nodes to have the external traversal
966// continue on to children. Return false if children were
967// already processed.
968//
969
970//
qining25262b32016-05-06 17:25:16 -0400971// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600972// - uniform/input reads
973// - output writes
974// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
975// - something simple that degenerates into the last bullet
976//
977void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
978{
qining75d1d802016-04-06 14:42:01 -0400979 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
980 if (symbol->getType().getQualifier().isSpecConstant())
981 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
982
John Kessenich140f3df2015-06-26 16:58:36 -0600983 // getSymbolId() will set up all the IO decorations on the first call.
984 // Formal function parameters were mapped during makeFunctions().
985 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700986
987 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
988 if (builder.isPointer(id)) {
989 spv::StorageClass sc = builder.getStorageClass(id);
990 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
991 iOSet.insert(id);
992 }
993
994 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700995 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600996 // Prepare to generate code for the access
997
998 // L-value chains will be computed left to right. We're on the symbol now,
999 // which is the left-most part of the access chain, so now is "clear" time,
1000 // followed by setting the base.
1001 builder.clearAccessChain();
1002
1003 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001004 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001005 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001006 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001007 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001008 // These are also pure R-values.
1009 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001010 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001011 builder.setAccessChainRValue(id);
1012 else
1013 builder.setAccessChainLValue(id);
1014 }
1015}
1016
1017bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1018{
qining40887662016-04-03 22:20:42 -04001019 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1020 if (node->getType().getQualifier().isSpecConstant())
1021 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1022
John Kessenich140f3df2015-06-26 16:58:36 -06001023 // First, handle special cases
1024 switch (node->getOp()) {
1025 case glslang::EOpAssign:
1026 case glslang::EOpAddAssign:
1027 case glslang::EOpSubAssign:
1028 case glslang::EOpMulAssign:
1029 case glslang::EOpVectorTimesMatrixAssign:
1030 case glslang::EOpVectorTimesScalarAssign:
1031 case glslang::EOpMatrixTimesScalarAssign:
1032 case glslang::EOpMatrixTimesMatrixAssign:
1033 case glslang::EOpDivAssign:
1034 case glslang::EOpModAssign:
1035 case glslang::EOpAndAssign:
1036 case glslang::EOpInclusiveOrAssign:
1037 case glslang::EOpExclusiveOrAssign:
1038 case glslang::EOpLeftShiftAssign:
1039 case glslang::EOpRightShiftAssign:
1040 // A bin-op assign "a += b" means the same thing as "a = a + b"
1041 // where a is evaluated before b. For a simple assignment, GLSL
1042 // says to evaluate the left before the right. So, always, left
1043 // node then right node.
1044 {
1045 // get the left l-value, save it away
1046 builder.clearAccessChain();
1047 node->getLeft()->traverse(this);
1048 spv::Builder::AccessChain lValue = builder.getAccessChain();
1049
1050 // evaluate the right
1051 builder.clearAccessChain();
1052 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001053 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001054
1055 if (node->getOp() != glslang::EOpAssign) {
1056 // the left is also an r-value
1057 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001058 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001059
1060 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001061 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001062 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001063 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1064 node->getType().getBasicType());
1065
1066 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001067 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001068 }
1069
1070 // store the result
1071 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001072 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001073
1074 // assignments are expressions having an rValue after they are evaluated...
1075 builder.clearAccessChain();
1076 builder.setAccessChainRValue(rValue);
1077 }
1078 return false;
1079 case glslang::EOpIndexDirect:
1080 case glslang::EOpIndexDirectStruct:
1081 {
1082 // Get the left part of the access chain.
1083 node->getLeft()->traverse(this);
1084
1085 // Add the next element in the chain
1086
David Netoa901ffe2016-06-08 14:11:40 +01001087 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001088 if (! node->getLeft()->getType().isArray() &&
1089 node->getLeft()->getType().isVector() &&
1090 node->getOp() == glslang::EOpIndexDirect) {
1091 // This is essentially a hard-coded vector swizzle of size 1,
1092 // so short circuit the access-chain stuff with a swizzle.
1093 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001094 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001095 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001096 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001097 int spvIndex = glslangIndex;
1098 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1099 node->getOp() == glslang::EOpIndexDirectStruct)
1100 {
1101 // This may be, e.g., an anonymous block-member selection, which generally need
1102 // index remapping due to hidden members in anonymous blocks.
1103 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1104 assert(remapper.size() > 0);
1105 spvIndex = remapper[glslangIndex];
1106 }
John Kessenichebb50532016-05-16 19:22:05 -06001107
David Netoa901ffe2016-06-08 14:11:40 +01001108 // normal case for indexing array or structure or block
1109 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1110
1111 // Add capabilities here for accessing PointSize and clip/cull distance.
1112 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001113 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001114 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001115 }
1116 }
1117 return false;
1118 case glslang::EOpIndexIndirect:
1119 {
1120 // Structure or array or vector indirection.
1121 // Will use native SPIR-V access-chain for struct and array indirection;
1122 // matrices are arrays of vectors, so will also work for a matrix.
1123 // Will use the access chain's 'component' for variable index into a vector.
1124
1125 // This adapter is building access chains left to right.
1126 // Set up the access chain to the left.
1127 node->getLeft()->traverse(this);
1128
1129 // save it so that computing the right side doesn't trash it
1130 spv::Builder::AccessChain partial = builder.getAccessChain();
1131
1132 // compute the next index in the chain
1133 builder.clearAccessChain();
1134 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001135 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001136
1137 // restore the saved access chain
1138 builder.setAccessChain(partial);
1139
1140 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001141 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001142 else
John Kessenichfa668da2015-09-13 14:46:30 -06001143 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001144 }
1145 return false;
1146 case glslang::EOpVectorSwizzle:
1147 {
1148 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001149 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001150 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001151 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001152 }
1153 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001154 case glslang::EOpMatrixSwizzle:
1155 logger->missingFunctionality("matrix swizzle");
1156 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001157 case glslang::EOpLogicalOr:
1158 case glslang::EOpLogicalAnd:
1159 {
1160
1161 // These may require short circuiting, but can sometimes be done as straight
1162 // binary operations. The right operand must be short circuited if it has
1163 // side effects, and should probably be if it is complex.
1164 if (isTrivial(node->getRight()->getAsTyped()))
1165 break; // handle below as a normal binary operation
1166 // otherwise, we need to do dynamic short circuiting on the right operand
1167 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1168 builder.clearAccessChain();
1169 builder.setAccessChainRValue(result);
1170 }
1171 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001172 default:
1173 break;
1174 }
1175
1176 // Assume generic binary op...
1177
John Kessenich32cfd492016-02-02 12:37:46 -07001178 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001179 builder.clearAccessChain();
1180 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001181 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001182
John Kessenich32cfd492016-02-02 12:37:46 -07001183 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001184 builder.clearAccessChain();
1185 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001186 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001187
John Kessenich32cfd492016-02-02 12:37:46 -07001188 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001189 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001190 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001191 convertGlslangToSpvType(node->getType()), left, right,
1192 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001193
John Kessenich50e57562015-12-21 21:21:11 -07001194 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001195 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001196 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001197 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001198 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001199 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001200 return false;
1201 }
John Kessenich140f3df2015-06-26 16:58:36 -06001202}
1203
1204bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1205{
qining40887662016-04-03 22:20:42 -04001206 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1207 if (node->getType().getQualifier().isSpecConstant())
1208 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1209
John Kessenichfc51d282015-08-19 13:34:18 -06001210 spv::Id result = spv::NoResult;
1211
1212 // try texturing first
1213 result = createImageTextureFunctionCall(node);
1214 if (result != spv::NoResult) {
1215 builder.clearAccessChain();
1216 builder.setAccessChainRValue(result);
1217
1218 return false; // done with this node
1219 }
1220
1221 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001222
1223 if (node->getOp() == glslang::EOpArrayLength) {
1224 // Quite special; won't want to evaluate the operand.
1225
1226 // Normal .length() would have been constant folded by the front-end.
1227 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001228 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001229 assert(node->getOperand()->getType().isRuntimeSizedArray());
1230 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1231 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001232 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1233 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001234
1235 builder.clearAccessChain();
1236 builder.setAccessChainRValue(length);
1237
1238 return false;
1239 }
1240
John Kessenichfc51d282015-08-19 13:34:18 -06001241 // Start by evaluating the operand
1242
John Kessenich8c8505c2016-07-26 12:50:38 -06001243 // Does it need a swizzle inversion? If so, evaluation is inverted;
1244 // operate first on the swizzle base, then apply the swizzle.
1245 spv::Id invertedType = spv::NoType;
1246 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1247 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1248 invertedType = getInvertedSwizzleType(*node->getOperand());
1249
John Kessenich140f3df2015-06-26 16:58:36 -06001250 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001251 if (invertedType != spv::NoType)
1252 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1253 else
1254 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001255
Rex Xufc618912015-09-09 16:42:49 +08001256 spv::Id operand = spv::NoResult;
1257
1258 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1259 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001260 node->getOp() == glslang::EOpAtomicCounter ||
1261 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001262 operand = builder.accessChainGetLValue(); // Special case l-value operands
1263 else
John Kessenich32cfd492016-02-02 12:37:46 -07001264 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001265
John Kessenichf6640762016-08-01 19:44:00 -06001266 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001267 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001268
1269 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001270 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001271 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001272
1273 // if not, then possibly an operation
1274 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001275 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001276
1277 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001278 if (invertedType)
1279 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1280
John Kessenich140f3df2015-06-26 16:58:36 -06001281 builder.clearAccessChain();
1282 builder.setAccessChainRValue(result);
1283
1284 return false; // done with this node
1285 }
1286
1287 // it must be a special case, check...
1288 switch (node->getOp()) {
1289 case glslang::EOpPostIncrement:
1290 case glslang::EOpPostDecrement:
1291 case glslang::EOpPreIncrement:
1292 case glslang::EOpPreDecrement:
1293 {
1294 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001295 spv::Id one = 0;
1296 if (node->getBasicType() == glslang::EbtFloat)
1297 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001298 else if (node->getBasicType() == glslang::EbtDouble)
1299 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001300#ifdef AMD_EXTENSIONS
1301 else if (node->getBasicType() == glslang::EbtFloat16)
1302 one = builder.makeFloat16Constant(1.0F);
1303#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001304 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1305 one = builder.makeInt64Constant(1);
1306 else
1307 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001308 glslang::TOperator op;
1309 if (node->getOp() == glslang::EOpPreIncrement ||
1310 node->getOp() == glslang::EOpPostIncrement)
1311 op = glslang::EOpAdd;
1312 else
1313 op = glslang::EOpSub;
1314
John Kessenichf6640762016-08-01 19:44:00 -06001315 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001316 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001317 convertGlslangToSpvType(node->getType()), operand, one,
1318 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001319 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001320
1321 // The result of operation is always stored, but conditionally the
1322 // consumed result. The consumed result is always an r-value.
1323 builder.accessChainStore(result);
1324 builder.clearAccessChain();
1325 if (node->getOp() == glslang::EOpPreIncrement ||
1326 node->getOp() == glslang::EOpPreDecrement)
1327 builder.setAccessChainRValue(result);
1328 else
1329 builder.setAccessChainRValue(operand);
1330 }
1331
1332 return false;
1333
1334 case glslang::EOpEmitStreamVertex:
1335 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1336 return false;
1337 case glslang::EOpEndStreamPrimitive:
1338 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1339 return false;
1340
1341 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001342 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001343 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001344 }
John Kessenich140f3df2015-06-26 16:58:36 -06001345}
1346
1347bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1348{
qining27e04a02016-04-14 16:40:20 -04001349 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1350 if (node->getType().getQualifier().isSpecConstant())
1351 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1352
John Kessenichfc51d282015-08-19 13:34:18 -06001353 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001354 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1355 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001356
1357 // try texturing
1358 result = createImageTextureFunctionCall(node);
1359 if (result != spv::NoResult) {
1360 builder.clearAccessChain();
1361 builder.setAccessChainRValue(result);
1362
1363 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001364 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001365 // "imageStore" is a special case, which has no result
1366 return false;
1367 }
John Kessenichfc51d282015-08-19 13:34:18 -06001368
John Kessenich140f3df2015-06-26 16:58:36 -06001369 glslang::TOperator binOp = glslang::EOpNull;
1370 bool reduceComparison = true;
1371 bool isMatrix = false;
1372 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001373 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001374
1375 assert(node->getOp());
1376
John Kessenichf6640762016-08-01 19:44:00 -06001377 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001378
1379 switch (node->getOp()) {
1380 case glslang::EOpSequence:
1381 {
1382 if (preVisit)
1383 ++sequenceDepth;
1384 else
1385 --sequenceDepth;
1386
1387 if (sequenceDepth == 1) {
1388 // If this is the parent node of all the functions, we want to see them
1389 // early, so all call points have actual SPIR-V functions to reference.
1390 // In all cases, still let the traverser visit the children for us.
1391 makeFunctions(node->getAsAggregate()->getSequence());
1392
John Kessenich6fccb3c2016-09-19 16:01:41 -06001393 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001394 // anything else gets there, so visit out of order, doing them all now.
1395 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1396
John Kessenich6a60c2f2016-12-08 21:01:59 -07001397 // 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 -06001398 // so do them manually.
1399 visitFunctions(node->getAsAggregate()->getSequence());
1400
1401 return false;
1402 }
1403
1404 return true;
1405 }
1406 case glslang::EOpLinkerObjects:
1407 {
1408 if (visit == glslang::EvPreVisit)
1409 linkageOnly = true;
1410 else
1411 linkageOnly = false;
1412
1413 return true;
1414 }
1415 case glslang::EOpComma:
1416 {
1417 // processing from left to right naturally leaves the right-most
1418 // lying around in the access chain
1419 glslang::TIntermSequence& glslangOperands = node->getSequence();
1420 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1421 glslangOperands[i]->traverse(this);
1422
1423 return false;
1424 }
1425 case glslang::EOpFunction:
1426 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001427 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001428 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001429 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001430 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001431 } else {
1432 handleFunctionEntry(node);
1433 }
1434 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001435 if (inEntryPoint)
1436 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001437 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001438 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001439 }
1440
1441 return true;
1442 case glslang::EOpParameters:
1443 // Parameters will have been consumed by EOpFunction processing, but not
1444 // the body, so we still visited the function node's children, making this
1445 // child redundant.
1446 return false;
1447 case glslang::EOpFunctionCall:
1448 {
1449 if (node->isUserDefined())
1450 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001451 // 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 -07001452 if (result) {
1453 builder.clearAccessChain();
1454 builder.setAccessChainRValue(result);
1455 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001456 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001457
1458 return false;
1459 }
1460 case glslang::EOpConstructMat2x2:
1461 case glslang::EOpConstructMat2x3:
1462 case glslang::EOpConstructMat2x4:
1463 case glslang::EOpConstructMat3x2:
1464 case glslang::EOpConstructMat3x3:
1465 case glslang::EOpConstructMat3x4:
1466 case glslang::EOpConstructMat4x2:
1467 case glslang::EOpConstructMat4x3:
1468 case glslang::EOpConstructMat4x4:
1469 case glslang::EOpConstructDMat2x2:
1470 case glslang::EOpConstructDMat2x3:
1471 case glslang::EOpConstructDMat2x4:
1472 case glslang::EOpConstructDMat3x2:
1473 case glslang::EOpConstructDMat3x3:
1474 case glslang::EOpConstructDMat3x4:
1475 case glslang::EOpConstructDMat4x2:
1476 case glslang::EOpConstructDMat4x3:
1477 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001478#ifdef AMD_EXTENSIONS
1479 case glslang::EOpConstructF16Mat2x2:
1480 case glslang::EOpConstructF16Mat2x3:
1481 case glslang::EOpConstructF16Mat2x4:
1482 case glslang::EOpConstructF16Mat3x2:
1483 case glslang::EOpConstructF16Mat3x3:
1484 case glslang::EOpConstructF16Mat3x4:
1485 case glslang::EOpConstructF16Mat4x2:
1486 case glslang::EOpConstructF16Mat4x3:
1487 case glslang::EOpConstructF16Mat4x4:
1488#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001489 isMatrix = true;
1490 // fall through
1491 case glslang::EOpConstructFloat:
1492 case glslang::EOpConstructVec2:
1493 case glslang::EOpConstructVec3:
1494 case glslang::EOpConstructVec4:
1495 case glslang::EOpConstructDouble:
1496 case glslang::EOpConstructDVec2:
1497 case glslang::EOpConstructDVec3:
1498 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001499#ifdef AMD_EXTENSIONS
1500 case glslang::EOpConstructFloat16:
1501 case glslang::EOpConstructF16Vec2:
1502 case glslang::EOpConstructF16Vec3:
1503 case glslang::EOpConstructF16Vec4:
1504#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001505 case glslang::EOpConstructBool:
1506 case glslang::EOpConstructBVec2:
1507 case glslang::EOpConstructBVec3:
1508 case glslang::EOpConstructBVec4:
1509 case glslang::EOpConstructInt:
1510 case glslang::EOpConstructIVec2:
1511 case glslang::EOpConstructIVec3:
1512 case glslang::EOpConstructIVec4:
1513 case glslang::EOpConstructUint:
1514 case glslang::EOpConstructUVec2:
1515 case glslang::EOpConstructUVec3:
1516 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001517 case glslang::EOpConstructInt64:
1518 case glslang::EOpConstructI64Vec2:
1519 case glslang::EOpConstructI64Vec3:
1520 case glslang::EOpConstructI64Vec4:
1521 case glslang::EOpConstructUint64:
1522 case glslang::EOpConstructU64Vec2:
1523 case glslang::EOpConstructU64Vec3:
1524 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001525 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001526 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001527 {
1528 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001529 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001530 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001531 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001532 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001533 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001534 std::vector<spv::Id> constituents;
1535 for (int c = 0; c < (int)arguments.size(); ++c)
1536 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001537 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001538 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001539 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001540 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001541 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001542
1543 builder.clearAccessChain();
1544 builder.setAccessChainRValue(constructed);
1545
1546 return false;
1547 }
1548
1549 // These six are component-wise compares with component-wise results.
1550 // Forward on to createBinaryOperation(), requesting a vector result.
1551 case glslang::EOpLessThan:
1552 case glslang::EOpGreaterThan:
1553 case glslang::EOpLessThanEqual:
1554 case glslang::EOpGreaterThanEqual:
1555 case glslang::EOpVectorEqual:
1556 case glslang::EOpVectorNotEqual:
1557 {
1558 // Map the operation to a binary
1559 binOp = node->getOp();
1560 reduceComparison = false;
1561 switch (node->getOp()) {
1562 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1563 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1564 default: binOp = node->getOp(); break;
1565 }
1566
1567 break;
1568 }
1569 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001570 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001571 binOp = glslang::EOpMul;
1572 break;
1573 case glslang::EOpOuterProduct:
1574 // two vectors multiplied to make a matrix
1575 binOp = glslang::EOpOuterProduct;
1576 break;
1577 case glslang::EOpDot:
1578 {
qining25262b32016-05-06 17:25:16 -04001579 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001580 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001581 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001582 binOp = glslang::EOpMul;
1583 break;
1584 }
1585 case glslang::EOpMod:
1586 // when an aggregate, this is the floating-point mod built-in function,
1587 // which can be emitted by the one in createBinaryOperation()
1588 binOp = glslang::EOpMod;
1589 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001590 case glslang::EOpEmitVertex:
1591 case glslang::EOpEndPrimitive:
1592 case glslang::EOpBarrier:
1593 case glslang::EOpMemoryBarrier:
1594 case glslang::EOpMemoryBarrierAtomicCounter:
1595 case glslang::EOpMemoryBarrierBuffer:
1596 case glslang::EOpMemoryBarrierImage:
1597 case glslang::EOpMemoryBarrierShared:
1598 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001599 case glslang::EOpAllMemoryBarrierWithGroupSync:
1600 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1601 case glslang::EOpWorkgroupMemoryBarrier:
1602 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001603 noReturnValue = true;
1604 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1605 break;
1606
John Kessenich426394d2015-07-23 10:22:48 -06001607 case glslang::EOpAtomicAdd:
1608 case glslang::EOpAtomicMin:
1609 case glslang::EOpAtomicMax:
1610 case glslang::EOpAtomicAnd:
1611 case glslang::EOpAtomicOr:
1612 case glslang::EOpAtomicXor:
1613 case glslang::EOpAtomicExchange:
1614 case glslang::EOpAtomicCompSwap:
1615 atomic = true;
1616 break;
1617
John Kessenich140f3df2015-06-26 16:58:36 -06001618 default:
1619 break;
1620 }
1621
1622 //
1623 // See if it maps to a regular operation.
1624 //
John Kessenich140f3df2015-06-26 16:58:36 -06001625 if (binOp != glslang::EOpNull) {
1626 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1627 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1628 assert(left && right);
1629
1630 builder.clearAccessChain();
1631 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001632 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001633
1634 builder.clearAccessChain();
1635 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001636 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001637
qining25262b32016-05-06 17:25:16 -04001638 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001639 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001640 left->getType().getBasicType(), reduceComparison);
1641
1642 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001643 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001644 builder.clearAccessChain();
1645 builder.setAccessChainRValue(result);
1646
1647 return false;
1648 }
1649
John Kessenich426394d2015-07-23 10:22:48 -06001650 //
1651 // Create the list of operands.
1652 //
John Kessenich140f3df2015-06-26 16:58:36 -06001653 glslang::TIntermSequence& glslangOperands = node->getSequence();
1654 std::vector<spv::Id> operands;
1655 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001656 // special case l-value operands; there are just a few
1657 bool lvalue = false;
1658 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001659 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001660 case glslang::EOpModf:
1661 if (arg == 1)
1662 lvalue = true;
1663 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001664 case glslang::EOpInterpolateAtSample:
1665 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001666#ifdef AMD_EXTENSIONS
1667 case glslang::EOpInterpolateAtVertex:
1668#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001669 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001670 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001671
1672 // Does it need a swizzle inversion? If so, evaluation is inverted;
1673 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001674 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001675 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1676 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1677 }
Rex Xu7a26c172015-12-08 17:12:09 +08001678 break;
Rex Xud4782c12015-09-06 16:30:11 +08001679 case glslang::EOpAtomicAdd:
1680 case glslang::EOpAtomicMin:
1681 case glslang::EOpAtomicMax:
1682 case glslang::EOpAtomicAnd:
1683 case glslang::EOpAtomicOr:
1684 case glslang::EOpAtomicXor:
1685 case glslang::EOpAtomicExchange:
1686 case glslang::EOpAtomicCompSwap:
1687 if (arg == 0)
1688 lvalue = true;
1689 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001690 case glslang::EOpAddCarry:
1691 case glslang::EOpSubBorrow:
1692 if (arg == 2)
1693 lvalue = true;
1694 break;
1695 case glslang::EOpUMulExtended:
1696 case glslang::EOpIMulExtended:
1697 if (arg >= 2)
1698 lvalue = true;
1699 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001700 default:
1701 break;
1702 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001703 builder.clearAccessChain();
1704 if (invertedType != spv::NoType && arg == 0)
1705 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1706 else
1707 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001708 if (lvalue)
1709 operands.push_back(builder.accessChainGetLValue());
1710 else
John Kessenich32cfd492016-02-02 12:37:46 -07001711 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001712 }
John Kessenich426394d2015-07-23 10:22:48 -06001713
1714 if (atomic) {
1715 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001716 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001717 } else {
1718 // Pass through to generic operations.
1719 switch (glslangOperands.size()) {
1720 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001721 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001722 break;
1723 case 1:
qining25262b32016-05-06 17:25:16 -04001724 result = createUnaryOperation(
1725 node->getOp(), precision,
1726 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001727 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001728 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001729 break;
1730 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001731 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001732 break;
1733 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001734 if (invertedType)
1735 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001736 }
1737
1738 if (noReturnValue)
1739 return false;
1740
1741 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001742 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001743 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001744 } else {
1745 builder.clearAccessChain();
1746 builder.setAccessChainRValue(result);
1747 return false;
1748 }
1749}
1750
John Kessenich433e9ff2017-01-26 20:31:11 -07001751// This path handles both if-then-else and ?:
1752// The if-then-else has a node type of void, while
1753// ?: has either a void or a non-void node type
1754//
1755// Leaving the result, when not void:
1756// GLSL only has r-values as the result of a :?, but
1757// if we have an l-value, that can be more efficient if it will
1758// become the base of a complex r-value expression, because the
1759// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001760bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1761{
John Kessenich433e9ff2017-01-26 20:31:11 -07001762 // See if it simple and safe to generate OpSelect instead of using control flow.
1763 // Crucially, side effects must be avoided, and there are performance trade-offs.
1764 // Return true if good idea (and safe) for OpSelect, false otherwise.
1765 const auto selectPolicy = [&]() -> bool {
1766 if (node->getBasicType() == glslang::EbtVoid)
1767 return false;
1768
1769 if (node->getTrueBlock() == nullptr ||
1770 node->getFalseBlock() == nullptr)
1771 return false;
1772
1773 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1774 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1775
1776 // return true if a single operand to ? : is okay for OpSelect
1777 const auto operandOkay = [](glslang::TIntermTyped* node) {
1778 return node->getAsSymbolNode() || node->getAsConstantUnion();
1779 };
1780
1781 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1782 operandOkay(node->getFalseBlock()->getAsTyped());
1783 };
1784
1785 // Emit OpSelect for this selection.
1786 const auto handleAsOpSelect = [&]() {
1787 node->getCondition()->traverse(this);
1788 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1789 node->getTrueBlock()->traverse(this);
1790 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1791 node->getFalseBlock()->traverse(this);
1792 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1793
1794 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1795 builder.clearAccessChain();
1796 builder.setAccessChainRValue(select);
1797 };
1798
1799 // Try for OpSelect
1800
1801 if (selectPolicy()) {
1802 handleAsOpSelect();
1803 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001804 }
1805
John Kessenich433e9ff2017-01-26 20:31:11 -07001806 // Instead, emit control flow...
1807
1808 // Don't handle results as temporaries, because there will be two names
1809 // and better to leave SSA to later passes.
1810 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1811 ? spv::NoResult
1812 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1813
John Kessenich140f3df2015-06-26 16:58:36 -06001814 // emit the condition before doing anything with selection
1815 node->getCondition()->traverse(this);
1816
1817 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001818 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001819
John Kessenich433e9ff2017-01-26 20:31:11 -07001820 // emit the "then" statement
1821 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001822 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001823 if (result != spv::NoResult)
1824 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001825 }
1826
John Kessenich433e9ff2017-01-26 20:31:11 -07001827 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001828 ifBuilder.makeBeginElse();
1829 // emit the "else" statement
1830 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001831 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001832 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001833 }
1834
John Kessenich433e9ff2017-01-26 20:31:11 -07001835 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001836 ifBuilder.makeEndIf();
1837
John Kessenich433e9ff2017-01-26 20:31:11 -07001838 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001839 // GLSL only has r-values as the result of a :?, but
1840 // if we have an l-value, that can be more efficient if it will
1841 // become the base of a complex r-value expression, because the
1842 // next layer copies r-values into memory to use the access-chain mechanism
1843 builder.clearAccessChain();
1844 builder.setAccessChainLValue(result);
1845 }
1846
1847 return false;
1848}
1849
1850bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1851{
1852 // emit and get the condition before doing anything with switch
1853 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001854 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001855
1856 // browse the children to sort out code segments
1857 int defaultSegment = -1;
1858 std::vector<TIntermNode*> codeSegments;
1859 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1860 std::vector<int> caseValues;
1861 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1862 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1863 TIntermNode* child = *c;
1864 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001865 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001866 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001867 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001868 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1869 } else
1870 codeSegments.push_back(child);
1871 }
1872
qining25262b32016-05-06 17:25:16 -04001873 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001874 // statements between the last case and the end of the switch statement
1875 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1876 (int)codeSegments.size() == defaultSegment)
1877 codeSegments.push_back(nullptr);
1878
1879 // make the switch statement
1880 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001881 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001882
1883 // emit all the code in the segments
1884 breakForLoop.push(false);
1885 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1886 builder.nextSwitchSegment(segmentBlocks, s);
1887 if (codeSegments[s])
1888 codeSegments[s]->traverse(this);
1889 else
1890 builder.addSwitchBreak();
1891 }
1892 breakForLoop.pop();
1893
1894 builder.endSwitch(segmentBlocks);
1895
1896 return false;
1897}
1898
1899void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1900{
1901 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001902 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001903
1904 builder.clearAccessChain();
1905 builder.setAccessChainRValue(constant);
1906}
1907
1908bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1909{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001910 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001911 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001912 // Spec requires back edges to target header blocks, and every header block
1913 // must dominate its merge block. Make a header block first to ensure these
1914 // conditions are met. By definition, it will contain OpLoopMerge, followed
1915 // by a block-ending branch. But we don't want to put any other body/test
1916 // instructions in it, since the body/test may have arbitrary instructions,
1917 // including merges of its own.
1918 builder.setBuildPoint(&blocks.head);
1919 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001920 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001921 spv::Block& test = builder.makeNewBlock();
1922 builder.createBranch(&test);
1923
1924 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001926 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001927 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001928 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1929
1930 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001931 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001932 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001933 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001934 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001935 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001936
1937 builder.setBuildPoint(&blocks.continue_target);
1938 if (node->getTerminal())
1939 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001940 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001941 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001942 builder.createBranch(&blocks.body);
1943
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001944 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001945 builder.setBuildPoint(&blocks.body);
1946 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001947 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001948 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001949 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001950
1951 builder.setBuildPoint(&blocks.continue_target);
1952 if (node->getTerminal())
1953 node->getTerminal()->traverse(this);
1954 if (node->getTest()) {
1955 node->getTest()->traverse(this);
1956 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001957 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001958 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001959 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001960 // TODO: unless there was a break/return/discard instruction
1961 // somewhere in the body, this is an infinite loop, so we should
1962 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001963 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001964 }
John Kessenich140f3df2015-06-26 16:58:36 -06001965 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001966 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001967 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001968 return false;
1969}
1970
1971bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1972{
1973 if (node->getExpression())
1974 node->getExpression()->traverse(this);
1975
1976 switch (node->getFlowOp()) {
1977 case glslang::EOpKill:
1978 builder.makeDiscard();
1979 break;
1980 case glslang::EOpBreak:
1981 if (breakForLoop.top())
1982 builder.createLoopExit();
1983 else
1984 builder.addSwitchBreak();
1985 break;
1986 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001987 builder.createLoopContinue();
1988 break;
1989 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001990 if (node->getExpression()) {
1991 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1992 spv::Id returnId = accessChainLoad(glslangReturnType);
1993 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1994 builder.clearAccessChain();
1995 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1996 builder.setAccessChainLValue(copyId);
1997 multiTypeStore(glslangReturnType, returnId);
1998 returnId = builder.createLoad(copyId);
1999 }
2000 builder.makeReturn(false, returnId);
2001 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002002 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002003
2004 builder.clearAccessChain();
2005 break;
2006
2007 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002008 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 break;
2010 }
2011
2012 return false;
2013}
2014
2015spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2016{
qining25262b32016-05-06 17:25:16 -04002017 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002018 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002019 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002020 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002021 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002022 }
2023
2024 // Now, handle actual variables
2025 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2026 spv::Id spvType = convertGlslangToSpvType(node->getType());
2027
2028 const char* name = node->getName().c_str();
2029 if (glslang::IsAnonymous(name))
2030 name = "";
2031
2032 return builder.createVariable(storageClass, spvType, name);
2033}
2034
2035// Return type Id of the sampled type.
2036spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2037{
2038 switch (sampler.type) {
2039 case glslang::EbtFloat: return builder.makeFloatType(32);
2040 case glslang::EbtInt: return builder.makeIntType(32);
2041 case glslang::EbtUint: return builder.makeUintType(32);
2042 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002043 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 return builder.makeFloatType(32);
2045 }
2046}
2047
John Kessenich8c8505c2016-07-26 12:50:38 -06002048// If node is a swizzle operation, return the type that should be used if
2049// the swizzle base is first consumed by another operation, before the swizzle
2050// is applied.
2051spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2052{
John Kessenichecba76f2017-01-06 00:34:48 -07002053 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002054 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2055 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2056 else
2057 return spv::NoType;
2058}
2059
2060// When inverting a swizzle with a parent op, this function
2061// will apply the swizzle operation to a completed parent operation.
2062spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2063{
2064 std::vector<unsigned> swizzle;
2065 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2066 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2067}
2068
John Kessenich8c8505c2016-07-26 12:50:38 -06002069// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2070void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2071{
2072 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2073 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2074 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2075}
2076
John Kessenich3ac051e2015-12-20 11:29:16 -07002077// Convert from a glslang type to an SPV type, by calling into a
2078// recursive version of this function. This establishes the inherited
2079// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002080spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2081{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002082 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002083}
2084
2085// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002086// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002087// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002088spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002089{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002090 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002091
2092 switch (type.getBasicType()) {
2093 case glslang::EbtVoid:
2094 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002095 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002096 break;
2097 case glslang::EbtFloat:
2098 spvType = builder.makeFloatType(32);
2099 break;
2100 case glslang::EbtDouble:
2101 spvType = builder.makeFloatType(64);
2102 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002103#ifdef AMD_EXTENSIONS
2104 case glslang::EbtFloat16:
2105 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002106 spvType = builder.makeFloatType(16);
2107 break;
2108#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002109 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002110 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2111 // a 32-bit int where non-0 means true.
2112 if (explicitLayout != glslang::ElpNone)
2113 spvType = builder.makeUintType(32);
2114 else
2115 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002116 break;
2117 case glslang::EbtInt:
2118 spvType = builder.makeIntType(32);
2119 break;
2120 case glslang::EbtUint:
2121 spvType = builder.makeUintType(32);
2122 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002123 case glslang::EbtInt64:
2124 builder.addCapability(spv::CapabilityInt64);
2125 spvType = builder.makeIntType(64);
2126 break;
2127 case glslang::EbtUint64:
2128 builder.addCapability(spv::CapabilityInt64);
2129 spvType = builder.makeUintType(64);
2130 break;
John Kessenich426394d2015-07-23 10:22:48 -06002131 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002132 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002133 spvType = builder.makeUintType(32);
2134 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002135 case glslang::EbtSampler:
2136 {
2137 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002138 if (sampler.sampler) {
2139 // pure sampler
2140 spvType = builder.makeSamplerType();
2141 } else {
2142 // an image is present, make its type
2143 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2144 sampler.image ? 2 : 1, TranslateImageFormat(type));
2145 if (sampler.combined) {
2146 // already has both image and sampler, make the combined type
2147 spvType = builder.makeSampledImageType(spvType);
2148 }
John Kessenich55e7d112015-11-15 21:33:39 -07002149 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002150 }
John Kessenich140f3df2015-06-26 16:58:36 -06002151 break;
2152 case glslang::EbtStruct:
2153 case glslang::EbtBlock:
2154 {
2155 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002156 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002157
2158 // Try to share structs for different layouts, but not yet for other
2159 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002160 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002161 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002162 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164
2165 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002166 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002167 memberRemapper[glslangMembers].resize(glslangMembers->size());
2168 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002169 }
2170 break;
2171 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002172 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002173 break;
2174 }
2175
2176 if (type.isMatrix())
2177 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2178 else {
2179 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2180 if (type.getVectorSize() > 1)
2181 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2182 }
2183
2184 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002185 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2186
John Kessenichc9a80832015-09-12 12:17:44 -06002187 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002188 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002189 // We need to decorate array strides for types needing explicit layout, except blocks.
2190 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002191 // Use a dummy glslang type for querying internal strides of
2192 // arrays of arrays, but using just a one-dimensional array.
2193 glslang::TType simpleArrayType(type, 0); // deference type of the array
2194 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2195 simpleArrayType.getArraySizes().dereference();
2196
2197 // Will compute the higher-order strides here, rather than making a whole
2198 // pile of types and doing repetitive recursion on their contents.
2199 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2200 }
John Kessenichf8842e52016-01-04 19:22:56 -07002201
2202 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002203 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002204 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002205 if (stride > 0)
2206 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002207 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002208 }
2209 } else {
2210 // single-dimensional array, and don't yet have stride
2211
John Kessenichf8842e52016-01-04 19:22:56 -07002212 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002213 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2214 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002215 }
John Kessenich31ed4832015-09-09 17:51:38 -06002216
John Kessenichc9a80832015-09-12 12:17:44 -06002217 // Do the outer dimension, which might not be known for a runtime-sized array
2218 if (type.isRuntimeSizedArray()) {
2219 spvType = builder.makeRuntimeArray(spvType);
2220 } else {
2221 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002222 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002223 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002224 if (stride > 0)
2225 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002226 }
2227
2228 return spvType;
2229}
2230
John Kessenich6090df02016-06-30 21:18:02 -06002231// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2232// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2233// Mutually recursive with convertGlslangToSpvType().
2234spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2235 const glslang::TTypeList* glslangMembers,
2236 glslang::TLayoutPacking explicitLayout,
2237 const glslang::TQualifier& qualifier)
2238{
2239 // Create a vector of struct types for SPIR-V to consume
2240 std::vector<spv::Id> spvMembers;
2241 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2242 int locationOffset = 0; // for use across struct members, when they are called recursively
2243 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2244 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2245 if (glslangMember.hiddenMember()) {
2246 ++memberDelta;
2247 if (type.getBasicType() == glslang::EbtBlock)
2248 memberRemapper[glslangMembers][i] = -1;
2249 } else {
2250 if (type.getBasicType() == glslang::EbtBlock)
2251 memberRemapper[glslangMembers][i] = i - memberDelta;
2252 // modify just this child's view of the qualifier
2253 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2254 InheritQualifiers(memberQualifier, qualifier);
2255
2256 // manually inherit location; it's more complex
2257 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2258 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2259 if (qualifier.hasLocation())
2260 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2261
2262 // recurse
2263 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2264 }
2265 }
2266
2267 // Make the SPIR-V type
2268 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002269 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002270 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2271
2272 // Decorate it
2273 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2274
2275 return spvType;
2276}
2277
2278void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2279 const glslang::TTypeList* glslangMembers,
2280 glslang::TLayoutPacking explicitLayout,
2281 const glslang::TQualifier& qualifier,
2282 spv::Id spvType)
2283{
2284 // Name and decorate the non-hidden members
2285 int offset = -1;
2286 int locationOffset = 0; // for use within the members of this struct
2287 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2288 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2289 int member = i;
2290 if (type.getBasicType() == glslang::EbtBlock)
2291 member = memberRemapper[glslangMembers][i];
2292
2293 // modify just this child's view of the qualifier
2294 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2295 InheritQualifiers(memberQualifier, qualifier);
2296
2297 // using -1 above to indicate a hidden member
2298 if (member >= 0) {
2299 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2300 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2301 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2302 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002303 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2304 type.getQualifier().storage == glslang::EvqVaryingOut) {
2305 if (type.getBasicType() == glslang::EbtBlock ||
2306 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002307 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2308 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2309 }
2310 }
2311 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2312
2313 if (qualifier.storage == glslang::EvqBuffer) {
2314 std::vector<spv::Decoration> memory;
2315 TranslateMemoryDecoration(memberQualifier, memory);
2316 for (unsigned int i = 0; i < memory.size(); ++i)
2317 addMemberDecoration(spvType, member, memory[i]);
2318 }
2319
John Kessenich2f47bc92016-06-30 21:47:35 -06002320 // Compute location decoration; tricky based on whether inheritance is at play and
2321 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002322 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2323 // probably move to the linker stage of the front end proper, and just have the
2324 // answer sitting already distributed throughout the individual member locations.
2325 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002326 // Ignore member locations if the container is an array, as that's
2327 // ill-specified and decisions have been made to not allow this anyway.
2328 // The object itself must have a location, and that comes out from decorating the object,
2329 // not the type (this code decorates types).
2330 if (! type.isArray()) {
2331 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2332 // struct members should not have explicit locations
2333 assert(type.getBasicType() != glslang::EbtStruct);
2334 location = memberQualifier.layoutLocation;
2335 } else if (type.getBasicType() != glslang::EbtBlock) {
2336 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2337 // The members, and their nested types, must not themselves have Location decorations.
2338 } else if (qualifier.hasLocation()) // inheritance
2339 location = qualifier.layoutLocation + locationOffset;
2340 }
John Kessenich6090df02016-06-30 21:18:02 -06002341 if (location >= 0)
2342 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2343
John Kessenich2f47bc92016-06-30 21:47:35 -06002344 if (qualifier.hasLocation()) // track for upcoming inheritance
2345 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2346
John Kessenich6090df02016-06-30 21:18:02 -06002347 // component, XFB, others
2348 if (glslangMember.getQualifier().hasComponent())
2349 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2350 if (glslangMember.getQualifier().hasXfbOffset())
2351 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2352 else if (explicitLayout != glslang::ElpNone) {
2353 // figure out what to do with offset, which is accumulating
2354 int nextOffset;
2355 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2356 if (offset >= 0)
2357 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2358 offset = nextOffset;
2359 }
2360
2361 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2362 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2363
2364 // built-in variable decorations
2365 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002366 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002367 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002368
2369#ifdef NV_EXTENSIONS
2370 if (builtIn == spv::BuiltInLayer) {
2371 // SPV_NV_viewport_array2 extension
2372 if (glslangMember.getQualifier().layoutViewportRelative){
2373 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2374 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2375 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2376 }
2377 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2378 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2379 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2380 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2381 }
2382 }
2383#endif
John Kessenich6090df02016-06-30 21:18:02 -06002384 }
2385 }
2386
2387 // Decorate the structure
2388 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2389 addDecoration(spvType, TranslateBlockDecoration(type));
2390 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2391 builder.addCapability(spv::CapabilityGeometryStreams);
2392 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2393 }
2394 if (glslangIntermediate->getXfbMode()) {
2395 builder.addCapability(spv::CapabilityTransformFeedback);
2396 if (type.getQualifier().hasXfbStride())
2397 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2398 if (type.getQualifier().hasXfbBuffer())
2399 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2400 }
2401}
2402
John Kessenich6c292d32016-02-15 20:58:50 -07002403// Turn the expression forming the array size into an id.
2404// This is not quite trivial, because of specialization constants.
2405// Sometimes, a raw constant is turned into an Id, and sometimes
2406// a specialization constant expression is.
2407spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2408{
2409 // First, see if this is sized with a node, meaning a specialization constant:
2410 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2411 if (specNode != nullptr) {
2412 builder.clearAccessChain();
2413 specNode->traverse(this);
2414 return accessChainLoad(specNode->getAsTyped()->getType());
2415 }
qining25262b32016-05-06 17:25:16 -04002416
John Kessenich6c292d32016-02-15 20:58:50 -07002417 // Otherwise, need a compile-time (front end) size, get it:
2418 int size = arraySizes.getDimSize(dim);
2419 assert(size > 0);
2420 return builder.makeUintConstant(size);
2421}
2422
John Kessenich103bef92016-02-08 21:38:15 -07002423// Wrap the builder's accessChainLoad to:
2424// - localize handling of RelaxedPrecision
2425// - use the SPIR-V inferred type instead of another conversion of the glslang type
2426// (avoids unnecessary work and possible type punning for structures)
2427// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002428spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2429{
John Kessenich103bef92016-02-08 21:38:15 -07002430 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2431 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2432
2433 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002434 if (type.getBasicType() == glslang::EbtBool) {
2435 if (builder.isScalarType(nominalTypeId)) {
2436 // Conversion for bool
2437 spv::Id boolType = builder.makeBoolType();
2438 if (nominalTypeId != boolType)
2439 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2440 } else if (builder.isVectorType(nominalTypeId)) {
2441 // Conversion for bvec
2442 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2443 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2444 if (nominalTypeId != bvecType)
2445 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2446 }
2447 }
John Kessenich103bef92016-02-08 21:38:15 -07002448
2449 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002450}
2451
Rex Xu27253232016-02-23 17:51:09 +08002452// Wrap the builder's accessChainStore to:
2453// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002454//
2455// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002456void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2457{
2458 // Need to convert to abstract types when necessary
2459 if (type.getBasicType() == glslang::EbtBool) {
2460 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2461
2462 if (builder.isScalarType(nominalTypeId)) {
2463 // Conversion for bool
2464 spv::Id boolType = builder.makeBoolType();
2465 if (nominalTypeId != boolType) {
2466 spv::Id zero = builder.makeUintConstant(0);
2467 spv::Id one = builder.makeUintConstant(1);
2468 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2469 }
2470 } else if (builder.isVectorType(nominalTypeId)) {
2471 // Conversion for bvec
2472 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2473 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2474 if (nominalTypeId != bvecType) {
2475 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2476 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2477 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2478 }
2479 }
2480 }
2481
2482 builder.accessChainStore(rvalue);
2483}
2484
John Kessenich4bf71552016-09-02 11:20:21 -06002485// For storing when types match at the glslang level, but not might match at the
2486// SPIR-V level.
2487//
2488// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002489// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002490// as in a member-decorated way.
2491//
2492// NOTE: This function can handle any store request; if it's not special it
2493// simplifies to a simple OpStore.
2494//
2495// Implicitly uses the existing builder.accessChain as the storage target.
2496void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2497{
John Kessenichb3e24e42016-09-11 12:33:43 -06002498 // we only do the complex path here if it's an aggregate
2499 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002500 accessChainStore(type, rValue);
2501 return;
2502 }
2503
John Kessenichb3e24e42016-09-11 12:33:43 -06002504 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002505 spv::Id rType = builder.getTypeId(rValue);
2506 spv::Id lValue = builder.accessChainGetLValue();
2507 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2508 if (lType == rType) {
2509 accessChainStore(type, rValue);
2510 return;
2511 }
2512
John Kessenichb3e24e42016-09-11 12:33:43 -06002513 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002514 // where the two types were the same type in GLSL. This requires member
2515 // by member copy, recursively.
2516
John Kessenichb3e24e42016-09-11 12:33:43 -06002517 // If an array, copy element by element.
2518 if (type.isArray()) {
2519 glslang::TType glslangElementType(type, 0);
2520 spv::Id elementRType = builder.getContainedTypeId(rType);
2521 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2522 // get the source member
2523 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002524
John Kessenichb3e24e42016-09-11 12:33:43 -06002525 // set up the target storage
2526 builder.clearAccessChain();
2527 builder.setAccessChainLValue(lValue);
2528 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002529
John Kessenichb3e24e42016-09-11 12:33:43 -06002530 // store the member
2531 multiTypeStore(glslangElementType, elementRValue);
2532 }
2533 } else {
2534 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002535
John Kessenichb3e24e42016-09-11 12:33:43 -06002536 // loop over structure members
2537 const glslang::TTypeList& members = *type.getStruct();
2538 for (int m = 0; m < (int)members.size(); ++m) {
2539 const glslang::TType& glslangMemberType = *members[m].type;
2540
2541 // get the source member
2542 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2543 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2544
2545 // set up the target storage
2546 builder.clearAccessChain();
2547 builder.setAccessChainLValue(lValue);
2548 builder.accessChainPush(builder.makeIntConstant(m));
2549
2550 // store the member
2551 multiTypeStore(glslangMemberType, memberRValue);
2552 }
John Kessenich4bf71552016-09-02 11:20:21 -06002553 }
2554}
2555
John Kessenichf85e8062015-12-19 13:57:10 -07002556// Decide whether or not this type should be
2557// decorated with offsets and strides, and if so
2558// whether std140 or std430 rules should be applied.
2559glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002560{
John Kessenichf85e8062015-12-19 13:57:10 -07002561 // has to be a block
2562 if (type.getBasicType() != glslang::EbtBlock)
2563 return glslang::ElpNone;
2564
2565 // has to be a uniform or buffer block
2566 if (type.getQualifier().storage != glslang::EvqUniform &&
2567 type.getQualifier().storage != glslang::EvqBuffer)
2568 return glslang::ElpNone;
2569
2570 // return the layout to use
2571 switch (type.getQualifier().layoutPacking) {
2572 case glslang::ElpStd140:
2573 case glslang::ElpStd430:
2574 return type.getQualifier().layoutPacking;
2575 default:
2576 return glslang::ElpNone;
2577 }
John Kessenich31ed4832015-09-09 17:51:38 -06002578}
2579
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002580// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002581int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002582{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002583 int size;
John Kessenich49987892015-12-29 17:11:44 -07002584 int stride;
2585 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002586
2587 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002588}
2589
John Kessenich49987892015-12-29 17:11:44 -07002590// 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 -07002591// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002592int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002593{
John Kessenich49987892015-12-29 17:11:44 -07002594 glslang::TType elementType;
2595 elementType.shallowCopy(matrixType);
2596 elementType.clearArraySizes();
2597
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002598 int size;
John Kessenich49987892015-12-29 17:11:44 -07002599 int stride;
2600 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2601
2602 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002603}
2604
John Kessenich5e4b1242015-08-06 22:53:06 -06002605// Given a member type of a struct, realign the current offset for it, and compute
2606// the next (not yet aligned) offset for the next member, which will get aligned
2607// on the next call.
2608// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2609// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2610// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002611void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002612 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002613{
2614 // this will get a positive value when deemed necessary
2615 nextOffset = -1;
2616
John Kessenich5e4b1242015-08-06 22:53:06 -06002617 // override anything in currentOffset with user-set offset
2618 if (memberType.getQualifier().hasOffset())
2619 currentOffset = memberType.getQualifier().layoutOffset;
2620
2621 // It could be that current linker usage in glslang updated all the layoutOffset,
2622 // in which case the following code does not matter. But, that's not quite right
2623 // once cross-compilation unit GLSL validation is done, as the original user
2624 // settings are needed in layoutOffset, and then the following will come into play.
2625
John Kessenichf85e8062015-12-19 13:57:10 -07002626 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002627 if (! memberType.getQualifier().hasOffset())
2628 currentOffset = -1;
2629
2630 return;
2631 }
2632
John Kessenichf85e8062015-12-19 13:57:10 -07002633 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002634 if (currentOffset < 0)
2635 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002636
John Kessenich5e4b1242015-08-06 22:53:06 -06002637 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2638 // but possibly not yet correctly aligned.
2639
2640 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002641 int dummyStride;
2642 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002643 glslang::RoundToPow2(currentOffset, memberAlignment);
2644 nextOffset = currentOffset + memberSize;
2645}
2646
David Netoa901ffe2016-06-08 14:11:40 +01002647void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002648{
David Netoa901ffe2016-06-08 14:11:40 +01002649 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2650 switch (glslangBuiltIn)
2651 {
2652 case glslang::EbvClipDistance:
2653 case glslang::EbvCullDistance:
2654 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002655#ifdef NV_EXTENSIONS
2656 case glslang::EbvLayer:
2657 case glslang::EbvViewportMaskNV:
2658 case glslang::EbvSecondaryPositionNV:
2659 case glslang::EbvSecondaryViewportMaskNV:
2660#endif
David Netoa901ffe2016-06-08 14:11:40 +01002661 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2662 // Alternately, we could just call this for any glslang built-in, since the
2663 // capability already guards against duplicates.
2664 TranslateBuiltInDecoration(glslangBuiltIn, false);
2665 break;
2666 default:
2667 // Capabilities were already generated when the struct was declared.
2668 break;
2669 }
John Kessenichebb50532016-05-16 19:22:05 -06002670}
2671
John Kessenich6fccb3c2016-09-19 16:01:41 -06002672bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002673{
John Kessenicheee9d532016-09-19 18:09:30 -06002674 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002675}
2676
2677// Make all the functions, skeletally, without actually visiting their bodies.
2678void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2679{
2680 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2681 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002682 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002683 continue;
2684
2685 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002686 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002687 //
qining25262b32016-05-06 17:25:16 -04002688 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002689 // function. What it is an address of varies:
2690 //
John Kessenich4bf71552016-09-02 11:20:21 -06002691 // - "in" parameters not marked as "const" can be written to without modifying the calling
2692 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002693 //
2694 // - "const in" parameters can just be the r-value, as no writes need occur.
2695 //
John Kessenich4bf71552016-09-02 11:20:21 -06002696 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2697 // 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 -06002698
2699 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002700 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002701 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2702
2703 for (int p = 0; p < (int)parameters.size(); ++p) {
2704 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2705 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002706 if (paramType.isOpaque())
2707 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2708 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002709 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2710 else
John Kessenich4bf71552016-09-02 11:20:21 -06002711 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002712 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002713 paramTypes.push_back(typeId);
2714 }
2715
2716 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002717 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2718 convertGlslangToSpvType(glslFunction->getType()),
2719 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002720
2721 // Track function to emit/call later
2722 functionMap[glslFunction->getName().c_str()] = function;
2723
2724 // Set the parameter id's
2725 for (int p = 0; p < (int)parameters.size(); ++p) {
2726 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2727 // give a name too
2728 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2729 }
2730 }
2731}
2732
2733// Process all the initializers, while skipping the functions and link objects
2734void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2735{
2736 builder.setBuildPoint(shaderEntry->getLastBlock());
2737 for (int i = 0; i < (int)initializers.size(); ++i) {
2738 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2739 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2740
2741 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002742 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002743 initializer->traverse(this);
2744 }
2745 }
2746}
2747
2748// Process all the functions, while skipping initializers.
2749void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2750{
2751 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2752 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002753 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002754 node->traverse(this);
2755 }
2756}
2757
2758void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2759{
qining25262b32016-05-06 17:25:16 -04002760 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002761 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002762 currentFunction = functionMap[node->getName().c_str()];
2763 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002764 builder.setBuildPoint(functionBlock);
2765}
2766
Rex Xu04db3f52015-09-16 11:44:02 +08002767void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002768{
Rex Xufc618912015-09-09 16:42:49 +08002769 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002770
2771 glslang::TSampler sampler = {};
2772 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002773 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002774 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2775 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2776 }
2777
John Kessenich140f3df2015-06-26 16:58:36 -06002778 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2779 builder.clearAccessChain();
2780 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002781
2782 // Special case l-value operands
2783 bool lvalue = false;
2784 switch (node.getOp()) {
2785 case glslang::EOpImageAtomicAdd:
2786 case glslang::EOpImageAtomicMin:
2787 case glslang::EOpImageAtomicMax:
2788 case glslang::EOpImageAtomicAnd:
2789 case glslang::EOpImageAtomicOr:
2790 case glslang::EOpImageAtomicXor:
2791 case glslang::EOpImageAtomicExchange:
2792 case glslang::EOpImageAtomicCompSwap:
2793 if (i == 0)
2794 lvalue = true;
2795 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002796 case glslang::EOpSparseImageLoad:
2797 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2798 lvalue = true;
2799 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002800 case glslang::EOpSparseTexture:
2801 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2802 lvalue = true;
2803 break;
2804 case glslang::EOpSparseTextureClamp:
2805 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2806 lvalue = true;
2807 break;
2808 case glslang::EOpSparseTextureLod:
2809 case glslang::EOpSparseTextureOffset:
2810 if (i == 3)
2811 lvalue = true;
2812 break;
2813 case glslang::EOpSparseTextureFetch:
2814 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2815 lvalue = true;
2816 break;
2817 case glslang::EOpSparseTextureFetchOffset:
2818 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2819 lvalue = true;
2820 break;
2821 case glslang::EOpSparseTextureLodOffset:
2822 case glslang::EOpSparseTextureGrad:
2823 case glslang::EOpSparseTextureOffsetClamp:
2824 if (i == 4)
2825 lvalue = true;
2826 break;
2827 case glslang::EOpSparseTextureGradOffset:
2828 case glslang::EOpSparseTextureGradClamp:
2829 if (i == 5)
2830 lvalue = true;
2831 break;
2832 case glslang::EOpSparseTextureGradOffsetClamp:
2833 if (i == 6)
2834 lvalue = true;
2835 break;
2836 case glslang::EOpSparseTextureGather:
2837 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2838 lvalue = true;
2839 break;
2840 case glslang::EOpSparseTextureGatherOffset:
2841 case glslang::EOpSparseTextureGatherOffsets:
2842 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2843 lvalue = true;
2844 break;
Rex Xufc618912015-09-09 16:42:49 +08002845 default:
2846 break;
2847 }
2848
Rex Xu6b86d492015-09-16 17:48:22 +08002849 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002850 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002851 else
John Kessenich32cfd492016-02-02 12:37:46 -07002852 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002853 }
2854}
2855
John Kessenichfc51d282015-08-19 13:34:18 -06002856void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002857{
John Kessenichfc51d282015-08-19 13:34:18 -06002858 builder.clearAccessChain();
2859 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002860 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002861}
John Kessenich140f3df2015-06-26 16:58:36 -06002862
John Kessenichfc51d282015-08-19 13:34:18 -06002863spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2864{
Rex Xufc618912015-09-09 16:42:49 +08002865 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002866 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002867 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002868 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002869
John Kessenichfc51d282015-08-19 13:34:18 -06002870 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002871 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2872 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2873 std::vector<spv::Id> arguments;
2874 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002875 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002876 else
2877 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002878 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002879
2880 spv::Builder::TextureParameters params = { };
2881 params.sampler = arguments[0];
2882
Rex Xu04db3f52015-09-16 11:44:02 +08002883 glslang::TCrackedTextureOp cracked;
2884 node->crackTexture(sampler, cracked);
2885
John Kessenichfc51d282015-08-19 13:34:18 -06002886 // Check for queries
2887 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002888 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2889 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002890 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002891
John Kessenichfc51d282015-08-19 13:34:18 -06002892 switch (node->getOp()) {
2893 case glslang::EOpImageQuerySize:
2894 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002895 if (arguments.size() > 1) {
2896 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002898 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002899 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002900 case glslang::EOpImageQuerySamples:
2901 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002902 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002903 case glslang::EOpTextureQueryLod:
2904 params.coords = arguments[1];
2905 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2906 case glslang::EOpTextureQueryLevels:
2907 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002908 case glslang::EOpSparseTexelsResident:
2909 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002910 default:
2911 assert(0);
2912 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002913 }
John Kessenich140f3df2015-06-26 16:58:36 -06002914 }
2915
Rex Xufc618912015-09-09 16:42:49 +08002916 // Check for image functions other than queries
2917 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002918 std::vector<spv::Id> operands;
2919 auto opIt = arguments.begin();
2920 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002921
2922 // Handle subpass operations
2923 // TODO: GLSL should change to have the "MS" only on the type rather than the
2924 // built-in function.
2925 if (cracked.subpass) {
2926 // add on the (0,0) coordinate
2927 spv::Id zero = builder.makeIntConstant(0);
2928 std::vector<spv::Id> comps;
2929 comps.push_back(zero);
2930 comps.push_back(zero);
2931 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2932 if (sampler.ms) {
2933 operands.push_back(spv::ImageOperandsSampleMask);
2934 operands.push_back(*(opIt++));
2935 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002936 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002937 }
2938
John Kessenich56bab042015-09-16 10:54:31 -06002939 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002940 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002941 if (sampler.ms) {
2942 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002943 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002944 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002945 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2946 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002947 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002948 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002949 if (sampler.ms) {
2950 operands.push_back(*(opIt + 1));
2951 operands.push_back(spv::ImageOperandsSampleMask);
2952 operands.push_back(*opIt);
2953 } else
2954 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002955 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002956 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2957 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002958 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002959 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2960 builder.addCapability(spv::CapabilitySparseResidency);
2961 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2962 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2963
2964 if (sampler.ms) {
2965 operands.push_back(spv::ImageOperandsSampleMask);
2966 operands.push_back(*opIt++);
2967 }
2968
2969 // Create the return type that was a special structure
2970 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002971 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002972 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2973 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2974
2975 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2976
2977 // Decode the return type
2978 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2979 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002980 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002981 // Process image atomic operations
2982
2983 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2984 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002985 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002986
John Kessenich8c8505c2016-07-26 12:50:38 -06002987 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002988 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002989
2990 std::vector<spv::Id> operands;
2991 operands.push_back(pointer);
2992 for (; opIt != arguments.end(); ++opIt)
2993 operands.push_back(*opIt);
2994
John Kessenich8c8505c2016-07-26 12:50:38 -06002995 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002996 }
2997 }
2998
2999 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003000 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003001 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3002
John Kessenichfc51d282015-08-19 13:34:18 -06003003 // check for bias argument
3004 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003005 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003006 int nonBiasArgCount = 2;
3007 if (cracked.offset)
3008 ++nonBiasArgCount;
3009 if (cracked.grad)
3010 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003011 if (cracked.lodClamp)
3012 ++nonBiasArgCount;
3013 if (sparse)
3014 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003015
3016 if ((int)arguments.size() > nonBiasArgCount)
3017 bias = true;
3018 }
3019
John Kessenicha5c33d62016-06-02 23:45:21 -06003020 // See if the sampler param should really be just the SPV image part
3021 if (cracked.fetch) {
3022 // a fetch needs to have the image extracted first
3023 if (builder.isSampledImage(params.sampler))
3024 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3025 }
3026
John Kessenichfc51d282015-08-19 13:34:18 -06003027 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003028
John Kessenichfc51d282015-08-19 13:34:18 -06003029 params.coords = arguments[1];
3030 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003031 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003032
3033 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003034 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003035 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003036 ++extraArgs;
3037 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003038 params.Dref = arguments[2];
3039 ++extraArgs;
3040 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003041 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003042 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003043 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003044 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003045 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003046 dRefComp = builder.getNumComponents(params.coords) - 1;
3047 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003048 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3049 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003050
3051 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003052 if (cracked.lod) {
3053 params.lod = arguments[2];
3054 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003055 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3056 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3057 noImplicitLod = true;
3058 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003059
3060 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003061 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003062 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003063 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003064 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003065
3066 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003067 if (cracked.grad) {
3068 params.gradX = arguments[2 + extraArgs];
3069 params.gradY = arguments[3 + extraArgs];
3070 extraArgs += 2;
3071 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003072
3073 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003074 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003075 params.offset = arguments[2 + extraArgs];
3076 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003077 } else if (cracked.offsets) {
3078 params.offsets = arguments[2 + extraArgs];
3079 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003080 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003081
3082 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003083 if (cracked.lodClamp) {
3084 params.lodClamp = arguments[2 + extraArgs];
3085 ++extraArgs;
3086 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003087
3088 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003089 if (sparse) {
3090 params.texelOut = arguments[2 + extraArgs];
3091 ++extraArgs;
3092 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003093
3094 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003095 if (bias) {
3096 params.bias = arguments[2 + extraArgs];
3097 ++extraArgs;
3098 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003099
3100 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003101 if (cracked.gather && ! sampler.shadow) {
3102 // default component is 0, if missing, otherwise an argument
3103 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003104 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003105 ++extraArgs;
3106 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003107 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003108 }
3109 }
John Kessenichfc51d282015-08-19 13:34:18 -06003110
John Kessenich65336482016-06-16 14:06:26 -06003111 // projective component (might not to move)
3112 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3113 // are divided by the last component of P."
3114 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3115 // unused components will appear after all used components."
3116 if (cracked.proj) {
3117 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3118 int projTargetComp;
3119 switch (sampler.dim) {
3120 case glslang::Esd1D: projTargetComp = 1; break;
3121 case glslang::Esd2D: projTargetComp = 2; break;
3122 case glslang::EsdRect: projTargetComp = 2; break;
3123 default: projTargetComp = projSourceComp; break;
3124 }
3125 // copy the projective coordinate if we have to
3126 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003127 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003128 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3129 projSourceComp);
3130 params.coords = builder.createCompositeInsert(projComp, params.coords,
3131 builder.getTypeId(params.coords), projTargetComp);
3132 }
3133 }
3134
John Kessenich8c8505c2016-07-26 12:50:38 -06003135 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003136}
3137
3138spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3139{
3140 // Grab the function's pointer from the previously created function
3141 spv::Function* function = functionMap[node->getName().c_str()];
3142 if (! function)
3143 return 0;
3144
3145 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3146 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3147
3148 // See comments in makeFunctions() for details about the semantics for parameter passing.
3149 //
3150 // These imply we need a four step process:
3151 // 1. Evaluate the arguments
3152 // 2. Allocate and make copies of in, out, and inout arguments
3153 // 3. Make the call
3154 // 4. Copy back the results
3155
3156 // 1. Evaluate the arguments
3157 std::vector<spv::Builder::AccessChain> lValues;
3158 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003159 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003160 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003161 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003162 // build l-value
3163 builder.clearAccessChain();
3164 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003165 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003166 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003167 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003168 // save l-value
3169 lValues.push_back(builder.getAccessChain());
3170 } else {
3171 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003172 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003173 }
3174 }
3175
3176 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3177 // copy the original into that space.
3178 //
3179 // Also, build up the list of actual arguments to pass in for the call
3180 int lValueCount = 0;
3181 int rValueCount = 0;
3182 std::vector<spv::Id> spvArgs;
3183 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003184 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003185 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003186 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003187 builder.setAccessChain(lValues[lValueCount]);
3188 arg = builder.accessChainGetLValue();
3189 ++lValueCount;
3190 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003191 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003192 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3193 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3194 // need to copy the input into output space
3195 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003196 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003197 builder.clearAccessChain();
3198 builder.setAccessChainLValue(arg);
3199 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003200 }
3201 ++lValueCount;
3202 } else {
3203 arg = rValues[rValueCount];
3204 ++rValueCount;
3205 }
3206 spvArgs.push_back(arg);
3207 }
3208
3209 // 3. Make the call.
3210 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003211 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003212
3213 // 4. Copy back out an "out" arguments.
3214 lValueCount = 0;
3215 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003216 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003217 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3218 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3219 spv::Id copy = builder.createLoad(spvArgs[a]);
3220 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003221 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003222 }
3223 ++lValueCount;
3224 }
3225 }
3226
3227 return result;
3228}
3229
3230// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003231spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3232 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003233 spv::Id typeId, spv::Id left, spv::Id right,
3234 glslang::TBasicType typeProxy, bool reduceComparison)
3235{
Rex Xu8ff43de2016-04-22 16:51:45 +08003236 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003237#ifdef AMD_EXTENSIONS
3238 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3239#else
John Kessenich140f3df2015-06-26 16:58:36 -06003240 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003241#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003242 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003243
3244 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003245 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003246 bool comparison = false;
3247
3248 switch (op) {
3249 case glslang::EOpAdd:
3250 case glslang::EOpAddAssign:
3251 if (isFloat)
3252 binOp = spv::OpFAdd;
3253 else
3254 binOp = spv::OpIAdd;
3255 break;
3256 case glslang::EOpSub:
3257 case glslang::EOpSubAssign:
3258 if (isFloat)
3259 binOp = spv::OpFSub;
3260 else
3261 binOp = spv::OpISub;
3262 break;
3263 case glslang::EOpMul:
3264 case glslang::EOpMulAssign:
3265 if (isFloat)
3266 binOp = spv::OpFMul;
3267 else
3268 binOp = spv::OpIMul;
3269 break;
3270 case glslang::EOpVectorTimesScalar:
3271 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003272 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003273 if (builder.isVector(right))
3274 std::swap(left, right);
3275 assert(builder.isScalar(right));
3276 needMatchingVectors = false;
3277 binOp = spv::OpVectorTimesScalar;
3278 } else
3279 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 break;
3281 case glslang::EOpVectorTimesMatrix:
3282 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003283 binOp = spv::OpVectorTimesMatrix;
3284 break;
3285 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003286 binOp = spv::OpMatrixTimesVector;
3287 break;
3288 case glslang::EOpMatrixTimesScalar:
3289 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003290 binOp = spv::OpMatrixTimesScalar;
3291 break;
3292 case glslang::EOpMatrixTimesMatrix:
3293 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003294 binOp = spv::OpMatrixTimesMatrix;
3295 break;
3296 case glslang::EOpOuterProduct:
3297 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003298 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003299 break;
3300
3301 case glslang::EOpDiv:
3302 case glslang::EOpDivAssign:
3303 if (isFloat)
3304 binOp = spv::OpFDiv;
3305 else if (isUnsigned)
3306 binOp = spv::OpUDiv;
3307 else
3308 binOp = spv::OpSDiv;
3309 break;
3310 case glslang::EOpMod:
3311 case glslang::EOpModAssign:
3312 if (isFloat)
3313 binOp = spv::OpFMod;
3314 else if (isUnsigned)
3315 binOp = spv::OpUMod;
3316 else
3317 binOp = spv::OpSMod;
3318 break;
3319 case glslang::EOpRightShift:
3320 case glslang::EOpRightShiftAssign:
3321 if (isUnsigned)
3322 binOp = spv::OpShiftRightLogical;
3323 else
3324 binOp = spv::OpShiftRightArithmetic;
3325 break;
3326 case glslang::EOpLeftShift:
3327 case glslang::EOpLeftShiftAssign:
3328 binOp = spv::OpShiftLeftLogical;
3329 break;
3330 case glslang::EOpAnd:
3331 case glslang::EOpAndAssign:
3332 binOp = spv::OpBitwiseAnd;
3333 break;
3334 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003335 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003336 binOp = spv::OpLogicalAnd;
3337 break;
3338 case glslang::EOpInclusiveOr:
3339 case glslang::EOpInclusiveOrAssign:
3340 binOp = spv::OpBitwiseOr;
3341 break;
3342 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003343 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003344 binOp = spv::OpLogicalOr;
3345 break;
3346 case glslang::EOpExclusiveOr:
3347 case glslang::EOpExclusiveOrAssign:
3348 binOp = spv::OpBitwiseXor;
3349 break;
3350 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003351 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003352 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003353 break;
3354
3355 case glslang::EOpLessThan:
3356 case glslang::EOpGreaterThan:
3357 case glslang::EOpLessThanEqual:
3358 case glslang::EOpGreaterThanEqual:
3359 case glslang::EOpEqual:
3360 case glslang::EOpNotEqual:
3361 case glslang::EOpVectorEqual:
3362 case glslang::EOpVectorNotEqual:
3363 comparison = true;
3364 break;
3365 default:
3366 break;
3367 }
3368
John Kessenich7c1aa102015-10-15 13:29:11 -06003369 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003370 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003371 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003372 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003373 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003374
3375 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003376 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003377 builder.promoteScalar(precision, left, right);
3378
qining25262b32016-05-06 17:25:16 -04003379 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3380 addDecoration(result, noContraction);
3381 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003382 }
3383
3384 if (! comparison)
3385 return 0;
3386
John Kessenich7c1aa102015-10-15 13:29:11 -06003387 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003388
John Kessenich4583b612016-08-07 19:14:22 -06003389 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3390 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003391 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003392
3393 switch (op) {
3394 case glslang::EOpLessThan:
3395 if (isFloat)
3396 binOp = spv::OpFOrdLessThan;
3397 else if (isUnsigned)
3398 binOp = spv::OpULessThan;
3399 else
3400 binOp = spv::OpSLessThan;
3401 break;
3402 case glslang::EOpGreaterThan:
3403 if (isFloat)
3404 binOp = spv::OpFOrdGreaterThan;
3405 else if (isUnsigned)
3406 binOp = spv::OpUGreaterThan;
3407 else
3408 binOp = spv::OpSGreaterThan;
3409 break;
3410 case glslang::EOpLessThanEqual:
3411 if (isFloat)
3412 binOp = spv::OpFOrdLessThanEqual;
3413 else if (isUnsigned)
3414 binOp = spv::OpULessThanEqual;
3415 else
3416 binOp = spv::OpSLessThanEqual;
3417 break;
3418 case glslang::EOpGreaterThanEqual:
3419 if (isFloat)
3420 binOp = spv::OpFOrdGreaterThanEqual;
3421 else if (isUnsigned)
3422 binOp = spv::OpUGreaterThanEqual;
3423 else
3424 binOp = spv::OpSGreaterThanEqual;
3425 break;
3426 case glslang::EOpEqual:
3427 case glslang::EOpVectorEqual:
3428 if (isFloat)
3429 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003430 else if (isBool)
3431 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003432 else
3433 binOp = spv::OpIEqual;
3434 break;
3435 case glslang::EOpNotEqual:
3436 case glslang::EOpVectorNotEqual:
3437 if (isFloat)
3438 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003439 else if (isBool)
3440 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003441 else
3442 binOp = spv::OpINotEqual;
3443 break;
3444 default:
3445 break;
3446 }
3447
qining25262b32016-05-06 17:25:16 -04003448 if (binOp != spv::OpNop) {
3449 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3450 addDecoration(result, noContraction);
3451 return builder.setPrecision(result, precision);
3452 }
John Kessenich140f3df2015-06-26 16:58:36 -06003453
3454 return 0;
3455}
3456
John Kessenich04bb8a02015-12-12 12:28:14 -07003457//
3458// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3459// These can be any of:
3460//
3461// matrix * scalar
3462// scalar * matrix
3463// matrix * matrix linear algebraic
3464// matrix * vector
3465// vector * matrix
3466// matrix * matrix componentwise
3467// matrix op matrix op in {+, -, /}
3468// matrix op scalar op in {+, -, /}
3469// scalar op matrix op in {+, -, /}
3470//
qining25262b32016-05-06 17:25:16 -04003471spv::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 -07003472{
3473 bool firstClass = true;
3474
3475 // First, handle first-class matrix operations (* and matrix/scalar)
3476 switch (op) {
3477 case spv::OpFDiv:
3478 if (builder.isMatrix(left) && builder.isScalar(right)) {
3479 // turn matrix / scalar into a multiply...
3480 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3481 op = spv::OpMatrixTimesScalar;
3482 } else
3483 firstClass = false;
3484 break;
3485 case spv::OpMatrixTimesScalar:
3486 if (builder.isMatrix(right))
3487 std::swap(left, right);
3488 assert(builder.isScalar(right));
3489 break;
3490 case spv::OpVectorTimesMatrix:
3491 assert(builder.isVector(left));
3492 assert(builder.isMatrix(right));
3493 break;
3494 case spv::OpMatrixTimesVector:
3495 assert(builder.isMatrix(left));
3496 assert(builder.isVector(right));
3497 break;
3498 case spv::OpMatrixTimesMatrix:
3499 assert(builder.isMatrix(left));
3500 assert(builder.isMatrix(right));
3501 break;
3502 default:
3503 firstClass = false;
3504 break;
3505 }
3506
qining25262b32016-05-06 17:25:16 -04003507 if (firstClass) {
3508 spv::Id result = builder.createBinOp(op, typeId, left, right);
3509 addDecoration(result, noContraction);
3510 return builder.setPrecision(result, precision);
3511 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003512
LoopDawg592860c2016-06-09 08:57:35 -06003513 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003514 // The result type of all of them is the same type as the (a) matrix operand.
3515 // The algorithm is to:
3516 // - break the matrix(es) into vectors
3517 // - smear any scalar to a vector
3518 // - do vector operations
3519 // - make a matrix out the vector results
3520 switch (op) {
3521 case spv::OpFAdd:
3522 case spv::OpFSub:
3523 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003524 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003525 case spv::OpFMul:
3526 {
3527 // one time set up...
3528 bool leftMat = builder.isMatrix(left);
3529 bool rightMat = builder.isMatrix(right);
3530 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3531 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3532 spv::Id scalarType = builder.getScalarTypeId(typeId);
3533 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3534 std::vector<spv::Id> results;
3535 spv::Id smearVec = spv::NoResult;
3536 if (builder.isScalar(left))
3537 smearVec = builder.smearScalar(precision, left, vecType);
3538 else if (builder.isScalar(right))
3539 smearVec = builder.smearScalar(precision, right, vecType);
3540
3541 // do each vector op
3542 for (unsigned int c = 0; c < numCols; ++c) {
3543 std::vector<unsigned int> indexes;
3544 indexes.push_back(c);
3545 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3546 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003547 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3548 addDecoration(result, noContraction);
3549 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003550 }
3551
3552 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003553 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003554 }
3555 default:
3556 assert(0);
3557 return spv::NoResult;
3558 }
3559}
3560
qining25262b32016-05-06 17:25:16 -04003561spv::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 -06003562{
3563 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003564 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003565 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003566 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003567#ifdef AMD_EXTENSIONS
3568 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3569#else
Rex Xu04db3f52015-09-16 11:44:02 +08003570 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003571#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003572
3573 switch (op) {
3574 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003575 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003576 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003577 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003578 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003579 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003580 unaryOp = spv::OpSNegate;
3581 break;
3582
3583 case glslang::EOpLogicalNot:
3584 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003585 unaryOp = spv::OpLogicalNot;
3586 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003587 case glslang::EOpBitwiseNot:
3588 unaryOp = spv::OpNot;
3589 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003590
John Kessenich140f3df2015-06-26 16:58:36 -06003591 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003592 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003593 break;
3594 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003595 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003596 break;
3597 case glslang::EOpTranspose:
3598 unaryOp = spv::OpTranspose;
3599 break;
3600
3601 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003602 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003603 break;
3604 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003605 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003606 break;
3607 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003608 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 break;
3610 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003611 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003612 break;
3613 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003614 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003615 break;
3616 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003617 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003618 break;
3619 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003620 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003621 break;
3622 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003623 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003624 break;
3625
3626 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003627 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003628 break;
3629 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003630 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003631 break;
3632 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003633 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003634 break;
3635 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003636 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003637 break;
3638 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
3644
3645 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003646 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003647 break;
3648 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003649 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651
3652 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003653 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003654 break;
3655 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003656 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003657 break;
3658 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003659 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003660 break;
3661 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003662 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003663 break;
3664 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003665 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003666 break;
3667 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003668 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003669 break;
3670
3671 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003672 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003673 break;
3674 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003675 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003676 break;
3677 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003678 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003679 break;
3680 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003681 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003682 break;
3683 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003684 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003685 break;
3686 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003687 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
3689
3690 case glslang::EOpIsNan:
3691 unaryOp = spv::OpIsNan;
3692 break;
3693 case glslang::EOpIsInf:
3694 unaryOp = spv::OpIsInf;
3695 break;
LoopDawg592860c2016-06-09 08:57:35 -06003696 case glslang::EOpIsFinite:
3697 unaryOp = spv::OpIsFinite;
3698 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003699
Rex Xucbc426e2015-12-15 16:03:10 +08003700 case glslang::EOpFloatBitsToInt:
3701 case glslang::EOpFloatBitsToUint:
3702 case glslang::EOpIntBitsToFloat:
3703 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003704 case glslang::EOpDoubleBitsToInt64:
3705 case glslang::EOpDoubleBitsToUint64:
3706 case glslang::EOpInt64BitsToDouble:
3707 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003708 unaryOp = spv::OpBitcast;
3709 break;
3710
John Kessenich140f3df2015-06-26 16:58:36 -06003711 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 break;
3726 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003727 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003729 case glslang::EOpPackSnorm4x8:
3730 libCall = spv::GLSLstd450PackSnorm4x8;
3731 break;
3732 case glslang::EOpUnpackSnorm4x8:
3733 libCall = spv::GLSLstd450UnpackSnorm4x8;
3734 break;
3735 case glslang::EOpPackUnorm4x8:
3736 libCall = spv::GLSLstd450PackUnorm4x8;
3737 break;
3738 case glslang::EOpUnpackUnorm4x8:
3739 libCall = spv::GLSLstd450UnpackUnorm4x8;
3740 break;
3741 case glslang::EOpPackDouble2x32:
3742 libCall = spv::GLSLstd450PackDouble2x32;
3743 break;
3744 case glslang::EOpUnpackDouble2x32:
3745 libCall = spv::GLSLstd450UnpackDouble2x32;
3746 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003747
Rex Xu8ff43de2016-04-22 16:51:45 +08003748 case glslang::EOpPackInt2x32:
3749 case glslang::EOpUnpackInt2x32:
3750 case glslang::EOpPackUint2x32:
3751 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003752 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003753 break;
3754
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003755#ifdef AMD_EXTENSIONS
3756 case glslang::EOpPackFloat2x16:
3757 case glslang::EOpUnpackFloat2x16:
3758 unaryOp = spv::OpBitcast;
3759 break;
3760#endif
3761
John Kessenich140f3df2015-06-26 16:58:36 -06003762 case glslang::EOpDPdx:
3763 unaryOp = spv::OpDPdx;
3764 break;
3765 case glslang::EOpDPdy:
3766 unaryOp = spv::OpDPdy;
3767 break;
3768 case glslang::EOpFwidth:
3769 unaryOp = spv::OpFwidth;
3770 break;
3771 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003772 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003773 unaryOp = spv::OpDPdxFine;
3774 break;
3775 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003776 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003777 unaryOp = spv::OpDPdyFine;
3778 break;
3779 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003780 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003781 unaryOp = spv::OpFwidthFine;
3782 break;
3783 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003784 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003785 unaryOp = spv::OpDPdxCoarse;
3786 break;
3787 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003788 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003789 unaryOp = spv::OpDPdyCoarse;
3790 break;
3791 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003792 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003793 unaryOp = spv::OpFwidthCoarse;
3794 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003795 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003796 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003797 libCall = spv::GLSLstd450InterpolateAtCentroid;
3798 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 case glslang::EOpAny:
3800 unaryOp = spv::OpAny;
3801 break;
3802 case glslang::EOpAll:
3803 unaryOp = spv::OpAll;
3804 break;
3805
3806 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003807 if (isFloat)
3808 libCall = spv::GLSLstd450FAbs;
3809 else
3810 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003811 break;
3812 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003813 if (isFloat)
3814 libCall = spv::GLSLstd450FSign;
3815 else
3816 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003817 break;
3818
John Kessenichfc51d282015-08-19 13:34:18 -06003819 case glslang::EOpAtomicCounterIncrement:
3820 case glslang::EOpAtomicCounterDecrement:
3821 case glslang::EOpAtomicCounter:
3822 {
3823 // Handle all of the atomics in one place, in createAtomicOperation()
3824 std::vector<spv::Id> operands;
3825 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003826 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003827 }
3828
John Kessenichfc51d282015-08-19 13:34:18 -06003829 case glslang::EOpBitFieldReverse:
3830 unaryOp = spv::OpBitReverse;
3831 break;
3832 case glslang::EOpBitCount:
3833 unaryOp = spv::OpBitCount;
3834 break;
3835 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003836 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003837 break;
3838 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003839 if (isUnsigned)
3840 libCall = spv::GLSLstd450FindUMsb;
3841 else
3842 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003843 break;
3844
Rex Xu574ab042016-04-14 16:53:07 +08003845 case glslang::EOpBallot:
3846 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003847 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003848 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003849 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003850#ifdef AMD_EXTENSIONS
3851 case glslang::EOpMinInvocations:
3852 case glslang::EOpMaxInvocations:
3853 case glslang::EOpAddInvocations:
3854 case glslang::EOpMinInvocationsNonUniform:
3855 case glslang::EOpMaxInvocationsNonUniform:
3856 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003857 case glslang::EOpMinInvocationsInclusiveScan:
3858 case glslang::EOpMaxInvocationsInclusiveScan:
3859 case glslang::EOpAddInvocationsInclusiveScan:
3860 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3861 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3862 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3863 case glslang::EOpMinInvocationsExclusiveScan:
3864 case glslang::EOpMaxInvocationsExclusiveScan:
3865 case glslang::EOpAddInvocationsExclusiveScan:
3866 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3867 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3868 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003869#endif
Rex Xu51596642016-09-21 18:56:12 +08003870 {
3871 std::vector<spv::Id> operands;
3872 operands.push_back(operand);
3873 return createInvocationsOperation(op, typeId, operands, typeProxy);
3874 }
Rex Xu9d93a232016-05-05 12:30:44 +08003875
3876#ifdef AMD_EXTENSIONS
3877 case glslang::EOpMbcnt:
3878 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3879 libCall = spv::MbcntAMD;
3880 break;
3881
3882 case glslang::EOpCubeFaceIndex:
3883 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3884 libCall = spv::CubeFaceIndexAMD;
3885 break;
3886
3887 case glslang::EOpCubeFaceCoord:
3888 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3889 libCall = spv::CubeFaceCoordAMD;
3890 break;
3891#endif
Rex Xu338b1852016-05-05 20:38:33 +08003892
John Kessenich140f3df2015-06-26 16:58:36 -06003893 default:
3894 return 0;
3895 }
3896
3897 spv::Id id;
3898 if (libCall >= 0) {
3899 std::vector<spv::Id> args;
3900 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003901 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003902 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003903 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003904 }
John Kessenich140f3df2015-06-26 16:58:36 -06003905
qining25262b32016-05-06 17:25:16 -04003906 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003907 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003908}
3909
John Kessenich7a53f762016-01-20 11:19:27 -07003910// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003911spv::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 -07003912{
3913 // Handle unary operations vector by vector.
3914 // The result type is the same type as the original type.
3915 // The algorithm is to:
3916 // - break the matrix into vectors
3917 // - apply the operation to each vector
3918 // - make a matrix out the vector results
3919
3920 // get the types sorted out
3921 int numCols = builder.getNumColumns(operand);
3922 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003923 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3924 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003925 std::vector<spv::Id> results;
3926
3927 // do each vector op
3928 for (int c = 0; c < numCols; ++c) {
3929 std::vector<unsigned int> indexes;
3930 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003931 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3932 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3933 addDecoration(destVec, noContraction);
3934 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003935 }
3936
3937 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003938 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003939}
3940
Rex Xu73e3ce72016-04-27 18:48:17 +08003941spv::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 -06003942{
3943 spv::Op convOp = spv::OpNop;
3944 spv::Id zero = 0;
3945 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003946 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003947
3948 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3949
3950 switch (op) {
3951 case glslang::EOpConvIntToBool:
3952 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003953 case glslang::EOpConvInt64ToBool:
3954 case glslang::EOpConvUint64ToBool:
3955 zero = (op == glslang::EOpConvInt64ToBool ||
3956 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003957 zero = makeSmearedConstant(zero, vectorSize);
3958 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3959
3960 case glslang::EOpConvFloatToBool:
3961 zero = builder.makeFloatConstant(0.0F);
3962 zero = makeSmearedConstant(zero, vectorSize);
3963 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3964
3965 case glslang::EOpConvDoubleToBool:
3966 zero = builder.makeDoubleConstant(0.0);
3967 zero = makeSmearedConstant(zero, vectorSize);
3968 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3969
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003970#ifdef AMD_EXTENSIONS
3971 case glslang::EOpConvFloat16ToBool:
3972 zero = builder.makeFloat16Constant(0.0F);
3973 zero = makeSmearedConstant(zero, vectorSize);
3974 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3975#endif
3976
John Kessenich140f3df2015-06-26 16:58:36 -06003977 case glslang::EOpConvBoolToFloat:
3978 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003979 zero = builder.makeFloatConstant(0.0F);
3980 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003981 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003982
John Kessenich140f3df2015-06-26 16:58:36 -06003983 case glslang::EOpConvBoolToDouble:
3984 convOp = spv::OpSelect;
3985 zero = builder.makeDoubleConstant(0.0);
3986 one = builder.makeDoubleConstant(1.0);
3987 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003988
3989#ifdef AMD_EXTENSIONS
3990 case glslang::EOpConvBoolToFloat16:
3991 convOp = spv::OpSelect;
3992 zero = builder.makeFloat16Constant(0.0F);
3993 one = builder.makeFloat16Constant(1.0F);
3994 break;
3995#endif
3996
John Kessenich140f3df2015-06-26 16:58:36 -06003997 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003998 case glslang::EOpConvBoolToInt64:
3999 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4000 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004001 convOp = spv::OpSelect;
4002 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004003
John Kessenich140f3df2015-06-26 16:58:36 -06004004 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004005 case glslang::EOpConvBoolToUint64:
4006 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4007 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004008 convOp = spv::OpSelect;
4009 break;
4010
4011 case glslang::EOpConvIntToFloat:
4012 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004013 case glslang::EOpConvInt64ToFloat:
4014 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004015#ifdef AMD_EXTENSIONS
4016 case glslang::EOpConvIntToFloat16:
4017 case glslang::EOpConvInt64ToFloat16:
4018#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004019 convOp = spv::OpConvertSToF;
4020 break;
4021
4022 case glslang::EOpConvUintToFloat:
4023 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004024 case glslang::EOpConvUint64ToFloat:
4025 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004026#ifdef AMD_EXTENSIONS
4027 case glslang::EOpConvUintToFloat16:
4028 case glslang::EOpConvUint64ToFloat16:
4029#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004030 convOp = spv::OpConvertUToF;
4031 break;
4032
4033 case glslang::EOpConvDoubleToFloat:
4034 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004035#ifdef AMD_EXTENSIONS
4036 case glslang::EOpConvDoubleToFloat16:
4037 case glslang::EOpConvFloat16ToDouble:
4038 case glslang::EOpConvFloatToFloat16:
4039 case glslang::EOpConvFloat16ToFloat:
4040#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004041 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004042 if (builder.isMatrixType(destType))
4043 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004044 break;
4045
4046 case glslang::EOpConvFloatToInt:
4047 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004048 case glslang::EOpConvFloatToInt64:
4049 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004050#ifdef AMD_EXTENSIONS
4051 case glslang::EOpConvFloat16ToInt:
4052 case glslang::EOpConvFloat16ToInt64:
4053#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004054 convOp = spv::OpConvertFToS;
4055 break;
4056
4057 case glslang::EOpConvUintToInt:
4058 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004059 case glslang::EOpConvUint64ToInt64:
4060 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004061 if (builder.isInSpecConstCodeGenMode()) {
4062 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004063 zero = (op == glslang::EOpConvUint64ToInt64 ||
4064 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004065 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004066 // Use OpIAdd, instead of OpBitcast to do the conversion when
4067 // generating for OpSpecConstantOp instruction.
4068 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4069 }
4070 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004071 convOp = spv::OpBitcast;
4072 break;
4073
4074 case glslang::EOpConvFloatToUint:
4075 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004076 case glslang::EOpConvFloatToUint64:
4077 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004078#ifdef AMD_EXTENSIONS
4079 case glslang::EOpConvFloat16ToUint:
4080 case glslang::EOpConvFloat16ToUint64:
4081#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004082 convOp = spv::OpConvertFToU;
4083 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004084
4085 case glslang::EOpConvIntToInt64:
4086 case glslang::EOpConvInt64ToInt:
4087 convOp = spv::OpSConvert;
4088 break;
4089
4090 case glslang::EOpConvUintToUint64:
4091 case glslang::EOpConvUint64ToUint:
4092 convOp = spv::OpUConvert;
4093 break;
4094
4095 case glslang::EOpConvIntToUint64:
4096 case glslang::EOpConvInt64ToUint:
4097 case glslang::EOpConvUint64ToInt:
4098 case glslang::EOpConvUintToInt64:
4099 // OpSConvert/OpUConvert + OpBitCast
4100 switch (op) {
4101 case glslang::EOpConvIntToUint64:
4102 convOp = spv::OpSConvert;
4103 type = builder.makeIntType(64);
4104 break;
4105 case glslang::EOpConvInt64ToUint:
4106 convOp = spv::OpSConvert;
4107 type = builder.makeIntType(32);
4108 break;
4109 case glslang::EOpConvUint64ToInt:
4110 convOp = spv::OpUConvert;
4111 type = builder.makeUintType(32);
4112 break;
4113 case glslang::EOpConvUintToInt64:
4114 convOp = spv::OpUConvert;
4115 type = builder.makeUintType(64);
4116 break;
4117 default:
4118 assert(0);
4119 break;
4120 }
4121
4122 if (vectorSize > 0)
4123 type = builder.makeVectorType(type, vectorSize);
4124
4125 operand = builder.createUnaryOp(convOp, type, operand);
4126
4127 if (builder.isInSpecConstCodeGenMode()) {
4128 // Build zero scalar or vector for OpIAdd.
4129 zero = (op == glslang::EOpConvIntToUint64 ||
4130 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4131 zero = makeSmearedConstant(zero, vectorSize);
4132 // Use OpIAdd, instead of OpBitcast to do the conversion when
4133 // generating for OpSpecConstantOp instruction.
4134 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4135 }
4136 // For normal run-time conversion instruction, use OpBitcast.
4137 convOp = spv::OpBitcast;
4138 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 default:
4140 break;
4141 }
4142
4143 spv::Id result = 0;
4144 if (convOp == spv::OpNop)
4145 return result;
4146
4147 if (convOp == spv::OpSelect) {
4148 zero = makeSmearedConstant(zero, vectorSize);
4149 one = makeSmearedConstant(one, vectorSize);
4150 result = builder.createTriOp(convOp, destType, operand, one, zero);
4151 } else
4152 result = builder.createUnaryOp(convOp, destType, operand);
4153
John Kessenich32cfd492016-02-02 12:37:46 -07004154 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004155}
4156
4157spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4158{
4159 if (vectorSize == 0)
4160 return constant;
4161
4162 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4163 std::vector<spv::Id> components;
4164 for (int c = 0; c < vectorSize; ++c)
4165 components.push_back(constant);
4166 return builder.makeCompositeConstant(vectorTypeId, components);
4167}
4168
John Kessenich426394d2015-07-23 10:22:48 -06004169// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004170spv::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 -06004171{
4172 spv::Op opCode = spv::OpNop;
4173
4174 switch (op) {
4175 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004176 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004177 opCode = spv::OpAtomicIAdd;
4178 break;
4179 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004180 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004181 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004182 break;
4183 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004184 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004185 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004186 break;
4187 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004188 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004189 opCode = spv::OpAtomicAnd;
4190 break;
4191 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004192 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004193 opCode = spv::OpAtomicOr;
4194 break;
4195 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004196 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004197 opCode = spv::OpAtomicXor;
4198 break;
4199 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004200 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004201 opCode = spv::OpAtomicExchange;
4202 break;
4203 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004204 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004205 opCode = spv::OpAtomicCompareExchange;
4206 break;
4207 case glslang::EOpAtomicCounterIncrement:
4208 opCode = spv::OpAtomicIIncrement;
4209 break;
4210 case glslang::EOpAtomicCounterDecrement:
4211 opCode = spv::OpAtomicIDecrement;
4212 break;
4213 case glslang::EOpAtomicCounter:
4214 opCode = spv::OpAtomicLoad;
4215 break;
4216 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004217 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004218 break;
4219 }
4220
4221 // Sort out the operands
4222 // - mapping from glslang -> SPV
4223 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004224 // - compare-exchange swaps the value and comparator
4225 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004226 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4227 auto opIt = operands.begin(); // walk the glslang operands
4228 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004229 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4230 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4231 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004232 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4233 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004234 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004235 spvAtomicOperands.push_back(*(opIt + 1));
4236 spvAtomicOperands.push_back(*opIt);
4237 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004238 }
John Kessenich426394d2015-07-23 10:22:48 -06004239
John Kessenich3e60a6f2015-09-14 22:45:16 -06004240 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004241 for (; opIt != operands.end(); ++opIt)
4242 spvAtomicOperands.push_back(*opIt);
4243
4244 return builder.createOp(opCode, typeId, spvAtomicOperands);
4245}
4246
John Kessenich91cef522016-05-05 16:45:40 -06004247// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004248spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004249{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004250#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004251 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004252 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004253#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004254
Rex Xu51596642016-09-21 18:56:12 +08004255 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004256 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004257 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4258
chaocf200da82016-12-20 12:44:35 -08004259 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4260 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004261 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4262 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004263 } else if (op == glslang::EOpAnyInvocation ||
4264 op == glslang::EOpAllInvocations ||
4265 op == glslang::EOpAllInvocationsEqual) {
4266 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4267 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004268 } else {
4269 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004270#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004271 if (op == glslang::EOpMinInvocationsNonUniform ||
4272 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004273 op == glslang::EOpAddInvocationsNonUniform ||
4274 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4275 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4276 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4277 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4278 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4279 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004280 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004281#endif
Rex Xu51596642016-09-21 18:56:12 +08004282
4283 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004284#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004285 switch (op) {
4286 case glslang::EOpMinInvocations:
4287 case glslang::EOpMaxInvocations:
4288 case glslang::EOpAddInvocations:
4289 case glslang::EOpMinInvocationsNonUniform:
4290 case glslang::EOpMaxInvocationsNonUniform:
4291 case glslang::EOpAddInvocationsNonUniform:
4292 groupOperation = spv::GroupOperationReduce;
4293 spvGroupOperands.push_back(groupOperation);
4294 break;
4295 case glslang::EOpMinInvocationsInclusiveScan:
4296 case glslang::EOpMaxInvocationsInclusiveScan:
4297 case glslang::EOpAddInvocationsInclusiveScan:
4298 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4299 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4300 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4301 groupOperation = spv::GroupOperationInclusiveScan;
4302 spvGroupOperands.push_back(groupOperation);
4303 break;
4304 case glslang::EOpMinInvocationsExclusiveScan:
4305 case glslang::EOpMaxInvocationsExclusiveScan:
4306 case glslang::EOpAddInvocationsExclusiveScan:
4307 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4308 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4309 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4310 groupOperation = spv::GroupOperationExclusiveScan;
4311 spvGroupOperands.push_back(groupOperation);
4312 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004313 default:
4314 break;
Rex Xu430ef402016-10-14 17:22:23 +08004315 }
Rex Xu9d93a232016-05-05 12:30:44 +08004316#endif
Rex Xu51596642016-09-21 18:56:12 +08004317 }
4318
4319 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4320 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004321
4322 switch (op) {
4323 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004324 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004325 break;
John Kessenich91cef522016-05-05 16:45:40 -06004326 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004327 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004328 break;
John Kessenich91cef522016-05-05 16:45:40 -06004329 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004330 opCode = spv::OpSubgroupAllEqualKHR;
4331 break;
Rex Xu51596642016-09-21 18:56:12 +08004332 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004333 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004334 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004335 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004336 break;
4337 case glslang::EOpReadFirstInvocation:
4338 opCode = spv::OpSubgroupFirstInvocationKHR;
4339 break;
4340 case glslang::EOpBallot:
4341 {
4342 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4343 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4344 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4345 //
4346 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4347 //
4348 spv::Id uintType = builder.makeUintType(32);
4349 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4350 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4351
4352 std::vector<spv::Id> components;
4353 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4354 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4355
4356 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4357 return builder.createUnaryOp(spv::OpBitcast, typeId,
4358 builder.createCompositeConstruct(uvec2Type, components));
4359 }
4360
Rex Xu9d93a232016-05-05 12:30:44 +08004361#ifdef AMD_EXTENSIONS
4362 case glslang::EOpMinInvocations:
4363 case glslang::EOpMaxInvocations:
4364 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004365 case glslang::EOpMinInvocationsInclusiveScan:
4366 case glslang::EOpMaxInvocationsInclusiveScan:
4367 case glslang::EOpAddInvocationsInclusiveScan:
4368 case glslang::EOpMinInvocationsExclusiveScan:
4369 case glslang::EOpMaxInvocationsExclusiveScan:
4370 case glslang::EOpAddInvocationsExclusiveScan:
4371 if (op == glslang::EOpMinInvocations ||
4372 op == glslang::EOpMinInvocationsInclusiveScan ||
4373 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004374 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004375 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004376 else {
4377 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004378 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004379 else
Rex Xu51596642016-09-21 18:56:12 +08004380 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004381 }
Rex Xu430ef402016-10-14 17:22:23 +08004382 } else if (op == glslang::EOpMaxInvocations ||
4383 op == glslang::EOpMaxInvocationsInclusiveScan ||
4384 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004385 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004386 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004387 else {
4388 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004389 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004390 else
Rex Xu51596642016-09-21 18:56:12 +08004391 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004392 }
4393 } else {
4394 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004395 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004396 else
Rex Xu51596642016-09-21 18:56:12 +08004397 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004398 }
4399
Rex Xu2bbbe062016-08-23 15:41:05 +08004400 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004401 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004402
4403 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004404 case glslang::EOpMinInvocationsNonUniform:
4405 case glslang::EOpMaxInvocationsNonUniform:
4406 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004407 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4408 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4409 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4410 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4411 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4412 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4413 if (op == glslang::EOpMinInvocationsNonUniform ||
4414 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4415 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004416 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004417 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004418 else {
4419 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004420 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004421 else
Rex Xu51596642016-09-21 18:56:12 +08004422 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004423 }
4424 }
Rex Xu430ef402016-10-14 17:22:23 +08004425 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4426 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4427 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004428 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004429 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004430 else {
4431 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004432 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004433 else
Rex Xu51596642016-09-21 18:56:12 +08004434 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004435 }
4436 }
4437 else {
4438 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004439 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004440 else
Rex Xu51596642016-09-21 18:56:12 +08004441 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004442 }
4443
Rex Xu2bbbe062016-08-23 15:41:05 +08004444 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004445 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004446
4447 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004448#endif
John Kessenich91cef522016-05-05 16:45:40 -06004449 default:
4450 logger->missingFunctionality("invocation operation");
4451 return spv::NoResult;
4452 }
Rex Xu51596642016-09-21 18:56:12 +08004453
4454 assert(opCode != spv::OpNop);
4455 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004456}
4457
Rex Xu2bbbe062016-08-23 15:41:05 +08004458// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004459spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004460{
Rex Xub7072052016-09-26 15:53:40 +08004461#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004462 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4463 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004464 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004465 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004466 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4467 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4468 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004469#else
4470 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4471 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004472 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4473 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004474#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004475
4476 // Handle group invocation operations scalar by scalar.
4477 // The result type is the same type as the original type.
4478 // The algorithm is to:
4479 // - break the vector into scalars
4480 // - apply the operation to each scalar
4481 // - make a vector out the scalar results
4482
4483 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004484 int numComponents = builder.getNumComponents(operands[0]);
4485 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004486 std::vector<spv::Id> results;
4487
4488 // do each scalar op
4489 for (int comp = 0; comp < numComponents; ++comp) {
4490 std::vector<unsigned int> indexes;
4491 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004492 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004493 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004494 if (op == spv::OpSubgroupReadInvocationKHR) {
4495 spvGroupOperands.push_back(scalar);
4496 spvGroupOperands.push_back(operands[1]);
4497 } else if (op == spv::OpGroupBroadcast) {
4498 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004499 spvGroupOperands.push_back(scalar);
4500 spvGroupOperands.push_back(operands[1]);
4501 } else {
chaocf200da82016-12-20 12:44:35 -08004502 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004503 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004504 spvGroupOperands.push_back(scalar);
4505 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004506
Rex Xub7072052016-09-26 15:53:40 +08004507 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004508 }
4509
4510 // put the pieces together
4511 return builder.createCompositeConstruct(typeId, results);
4512}
Rex Xu2bbbe062016-08-23 15:41:05 +08004513
John Kessenich5e4b1242015-08-06 22:53:06 -06004514spv::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 -06004515{
Rex Xu8ff43de2016-04-22 16:51:45 +08004516 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004517#ifdef AMD_EXTENSIONS
4518 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4519#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004520 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004521#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004522
John Kessenich140f3df2015-06-26 16:58:36 -06004523 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004524 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004525 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004526 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004527 spv::Id typeId0 = 0;
4528 if (consumedOperands > 0)
4529 typeId0 = builder.getTypeId(operands[0]);
4530 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004531
4532 switch (op) {
4533 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004534 if (isFloat)
4535 libCall = spv::GLSLstd450FMin;
4536 else if (isUnsigned)
4537 libCall = spv::GLSLstd450UMin;
4538 else
4539 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004540 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004541 break;
4542 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004543 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004544 break;
4545 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004546 if (isFloat)
4547 libCall = spv::GLSLstd450FMax;
4548 else if (isUnsigned)
4549 libCall = spv::GLSLstd450UMax;
4550 else
4551 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004552 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004553 break;
4554 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004555 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004556 break;
4557 case glslang::EOpDot:
4558 opCode = spv::OpDot;
4559 break;
4560 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004561 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004562 break;
4563
4564 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004565 if (isFloat)
4566 libCall = spv::GLSLstd450FClamp;
4567 else if (isUnsigned)
4568 libCall = spv::GLSLstd450UClamp;
4569 else
4570 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004571 builder.promoteScalar(precision, operands.front(), operands[1]);
4572 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004573 break;
4574 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004575 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4576 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004577 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004578 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004579 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004580 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004581 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004582 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004583 break;
4584 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004585 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004586 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004587 break;
4588 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004589 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004590 builder.promoteScalar(precision, operands[0], operands[2]);
4591 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004592 break;
4593
4594 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004595 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004596 break;
4597 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004598 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004599 break;
4600 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004601 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004602 break;
4603 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004604 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004605 break;
4606 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004607 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004608 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004609 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004610 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004611 libCall = spv::GLSLstd450InterpolateAtSample;
4612 break;
4613 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004614 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004615 libCall = spv::GLSLstd450InterpolateAtOffset;
4616 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004617 case glslang::EOpAddCarry:
4618 opCode = spv::OpIAddCarry;
4619 typeId = builder.makeStructResultType(typeId0, typeId0);
4620 consumedOperands = 2;
4621 break;
4622 case glslang::EOpSubBorrow:
4623 opCode = spv::OpISubBorrow;
4624 typeId = builder.makeStructResultType(typeId0, typeId0);
4625 consumedOperands = 2;
4626 break;
4627 case glslang::EOpUMulExtended:
4628 opCode = spv::OpUMulExtended;
4629 typeId = builder.makeStructResultType(typeId0, typeId0);
4630 consumedOperands = 2;
4631 break;
4632 case glslang::EOpIMulExtended:
4633 opCode = spv::OpSMulExtended;
4634 typeId = builder.makeStructResultType(typeId0, typeId0);
4635 consumedOperands = 2;
4636 break;
4637 case glslang::EOpBitfieldExtract:
4638 if (isUnsigned)
4639 opCode = spv::OpBitFieldUExtract;
4640 else
4641 opCode = spv::OpBitFieldSExtract;
4642 break;
4643 case glslang::EOpBitfieldInsert:
4644 opCode = spv::OpBitFieldInsert;
4645 break;
4646
4647 case glslang::EOpFma:
4648 libCall = spv::GLSLstd450Fma;
4649 break;
4650 case glslang::EOpFrexp:
4651 libCall = spv::GLSLstd450FrexpStruct;
4652 if (builder.getNumComponents(operands[0]) == 1)
4653 frexpIntType = builder.makeIntegerType(32, true);
4654 else
4655 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4656 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4657 consumedOperands = 1;
4658 break;
4659 case glslang::EOpLdexp:
4660 libCall = spv::GLSLstd450Ldexp;
4661 break;
4662
Rex Xu574ab042016-04-14 16:53:07 +08004663 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004664 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004665
Rex Xu9d93a232016-05-05 12:30:44 +08004666#ifdef AMD_EXTENSIONS
4667 case glslang::EOpSwizzleInvocations:
4668 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4669 libCall = spv::SwizzleInvocationsAMD;
4670 break;
4671 case glslang::EOpSwizzleInvocationsMasked:
4672 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4673 libCall = spv::SwizzleInvocationsMaskedAMD;
4674 break;
4675 case glslang::EOpWriteInvocation:
4676 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4677 libCall = spv::WriteInvocationAMD;
4678 break;
4679
4680 case glslang::EOpMin3:
4681 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4682 if (isFloat)
4683 libCall = spv::FMin3AMD;
4684 else {
4685 if (isUnsigned)
4686 libCall = spv::UMin3AMD;
4687 else
4688 libCall = spv::SMin3AMD;
4689 }
4690 break;
4691 case glslang::EOpMax3:
4692 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4693 if (isFloat)
4694 libCall = spv::FMax3AMD;
4695 else {
4696 if (isUnsigned)
4697 libCall = spv::UMax3AMD;
4698 else
4699 libCall = spv::SMax3AMD;
4700 }
4701 break;
4702 case glslang::EOpMid3:
4703 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4704 if (isFloat)
4705 libCall = spv::FMid3AMD;
4706 else {
4707 if (isUnsigned)
4708 libCall = spv::UMid3AMD;
4709 else
4710 libCall = spv::SMid3AMD;
4711 }
4712 break;
4713
4714 case glslang::EOpInterpolateAtVertex:
4715 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4716 libCall = spv::InterpolateAtVertexAMD;
4717 break;
4718#endif
4719
John Kessenich140f3df2015-06-26 16:58:36 -06004720 default:
4721 return 0;
4722 }
4723
4724 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004725 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004726 // Use an extended instruction from the standard library.
4727 // Construct the call arguments, without modifying the original operands vector.
4728 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4729 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004730 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004731 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004732 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004733 case 0:
4734 // should all be handled by visitAggregate and createNoArgOperation
4735 assert(0);
4736 return 0;
4737 case 1:
4738 // should all be handled by createUnaryOperation
4739 assert(0);
4740 return 0;
4741 case 2:
4742 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4743 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004744 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004745 // anything 3 or over doesn't have l-value operands, so all should be consumed
4746 assert(consumedOperands == operands.size());
4747 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004748 break;
4749 }
4750 }
4751
John Kessenich55e7d112015-11-15 21:33:39 -07004752 // Decode the return types that were structures
4753 switch (op) {
4754 case glslang::EOpAddCarry:
4755 case glslang::EOpSubBorrow:
4756 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4757 id = builder.createCompositeExtract(id, typeId0, 0);
4758 break;
4759 case glslang::EOpUMulExtended:
4760 case glslang::EOpIMulExtended:
4761 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4762 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4763 break;
4764 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004765 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004766 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4767 id = builder.createCompositeExtract(id, typeId0, 0);
4768 break;
4769 default:
4770 break;
4771 }
4772
John Kessenich32cfd492016-02-02 12:37:46 -07004773 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004774}
4775
Rex Xu9d93a232016-05-05 12:30:44 +08004776// Intrinsics with no arguments (or no return value, and no precision).
4777spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004778{
4779 // TODO: get the barrier operands correct
4780
4781 switch (op) {
4782 case glslang::EOpEmitVertex:
4783 builder.createNoResultOp(spv::OpEmitVertex);
4784 return 0;
4785 case glslang::EOpEndPrimitive:
4786 builder.createNoResultOp(spv::OpEndPrimitive);
4787 return 0;
4788 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004789 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004790 return 0;
4791 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004792 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004793 return 0;
4794 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004795 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004796 return 0;
4797 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004798 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004799 return 0;
4800 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004801 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004802 return 0;
4803 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004804 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004805 return 0;
4806 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004807 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004808 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004809 case glslang::EOpAllMemoryBarrierWithGroupSync:
4810 // Control barrier with non-"None" semantic is also a memory barrier.
4811 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4812 return 0;
4813 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4814 // Control barrier with non-"None" semantic is also a memory barrier.
4815 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4816 return 0;
4817 case glslang::EOpWorkgroupMemoryBarrier:
4818 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4819 return 0;
4820 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4821 // Control barrier with non-"None" semantic is also a memory barrier.
4822 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4823 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004824#ifdef AMD_EXTENSIONS
4825 case glslang::EOpTime:
4826 {
4827 std::vector<spv::Id> args; // Dummy arguments
4828 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4829 return builder.setPrecision(id, precision);
4830 }
4831#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004832 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004833 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004834 return 0;
4835 }
4836}
4837
4838spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4839{
John Kessenich2f273362015-07-18 22:34:27 -06004840 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004841 spv::Id id;
4842 if (symbolValues.end() != iter) {
4843 id = iter->second;
4844 return id;
4845 }
4846
4847 // it was not found, create it
4848 id = createSpvVariable(symbol);
4849 symbolValues[symbol->getId()] = id;
4850
Rex Xuc884b4a2016-06-29 15:03:44 +08004851 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004852 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004853 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004854 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004855 if (symbol->getType().getQualifier().hasSpecConstantId())
4856 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004857 if (symbol->getQualifier().hasIndex())
4858 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4859 if (symbol->getQualifier().hasComponent())
4860 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4861 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004862 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004863 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004864 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004865 if (symbol->getQualifier().hasXfbBuffer())
4866 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4867 if (symbol->getQualifier().hasXfbOffset())
4868 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4869 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004870 // atomic counters use this:
4871 if (symbol->getQualifier().hasOffset())
4872 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004873 }
4874
scygan2c864272016-05-18 18:09:17 +02004875 if (symbol->getQualifier().hasLocation())
4876 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004877 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004878 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004879 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004880 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004881 }
John Kessenich140f3df2015-06-26 16:58:36 -06004882 if (symbol->getQualifier().hasSet())
4883 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004884 else if (IsDescriptorResource(symbol->getType())) {
4885 // default to 0
4886 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4887 }
John Kessenich140f3df2015-06-26 16:58:36 -06004888 if (symbol->getQualifier().hasBinding())
4889 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004890 if (symbol->getQualifier().hasAttachment())
4891 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004892 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004893 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004894 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004895 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004896 if (symbol->getQualifier().hasXfbBuffer())
4897 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4898 }
4899
Rex Xu1da878f2016-02-21 20:59:01 +08004900 if (symbol->getType().isImage()) {
4901 std::vector<spv::Decoration> memory;
4902 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4903 for (unsigned int i = 0; i < memory.size(); ++i)
4904 addDecoration(id, memory[i]);
4905 }
4906
John Kessenich140f3df2015-06-26 16:58:36 -06004907 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004908 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004909 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004910 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004911
John Kessenichecba76f2017-01-06 00:34:48 -07004912#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004913 if (builtIn == spv::BuiltInSampleMask) {
4914 spv::Decoration decoration;
4915 // GL_NV_sample_mask_override_coverage extension
4916 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004917 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004918 else
4919 decoration = (spv::Decoration)spv::DecorationMax;
4920 addDecoration(id, decoration);
4921 if (decoration != spv::DecorationMax) {
4922 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4923 }
4924 }
chaoc771d89f2017-01-13 01:10:53 -08004925 else if (builtIn == spv::BuiltInLayer) {
4926 // SPV_NV_viewport_array2 extension
4927 if (symbol->getQualifier().layoutViewportRelative)
4928 {
4929 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4930 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4931 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4932 }
4933 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4934 {
4935 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4936 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4937 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4938 }
4939 }
4940
chaoc6e5acae2016-12-20 13:28:52 -08004941 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004942 addDecoration(id, spv::DecorationPassthroughNV);
4943 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004944 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4945 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004946#endif
4947
John Kessenich140f3df2015-06-26 16:58:36 -06004948 return id;
4949}
4950
John Kessenich55e7d112015-11-15 21:33:39 -07004951// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004952void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4953{
John Kessenich4016e382016-07-15 11:53:56 -06004954 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004955 builder.addDecoration(id, dec);
4956}
4957
John Kessenich55e7d112015-11-15 21:33:39 -07004958// If 'dec' is valid, add a one-operand decoration to an object
4959void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4960{
John Kessenich4016e382016-07-15 11:53:56 -06004961 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004962 builder.addDecoration(id, dec, value);
4963}
4964
4965// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004966void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4967{
John Kessenich4016e382016-07-15 11:53:56 -06004968 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004969 builder.addMemberDecoration(id, (unsigned)member, dec);
4970}
4971
John Kessenich92187592016-02-01 13:45:25 -07004972// If 'dec' is valid, add a one-operand decoration to a struct member
4973void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4974{
John Kessenich4016e382016-07-15 11:53:56 -06004975 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004976 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4977}
4978
John Kessenich55e7d112015-11-15 21:33:39 -07004979// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004980// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004981//
4982// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4983//
4984// Recursively walk the nodes. The nodes form a tree whose leaves are
4985// regular constants, which themselves are trees that createSpvConstant()
4986// recursively walks. So, this function walks the "top" of the tree:
4987// - emit specialization constant-building instructions for specConstant
4988// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004989spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004990{
John Kessenich7cc0e282016-03-20 00:46:02 -06004991 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004992
qining4f4bb812016-04-03 23:55:17 -04004993 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004994 if (! node.getQualifier().specConstant) {
4995 // hand off to the non-spec-constant path
4996 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4997 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004998 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004999 nextConst, false);
5000 }
5001
5002 // We now know we have a specialization constant to build
5003
John Kessenichd94c0032016-05-30 19:29:40 -06005004 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005005 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5006 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5007 std::vector<spv::Id> dimConstId;
5008 for (int dim = 0; dim < 3; ++dim) {
5009 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5010 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5011 if (specConst)
5012 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5013 }
5014 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5015 }
5016
5017 // An AST node labelled as specialization constant should be a symbol node.
5018 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5019 if (auto* sn = node.getAsSymbolNode()) {
5020 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005021 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5022 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5023 // will set the builder into spec constant op instruction generating mode.
5024 sub_tree->traverse(this);
5025 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005026 } else if (auto* const_union_array = &sn->getConstArray()){
5027 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005028 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5029 builder.addName(id, sn->getName().c_str());
5030 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005031 }
5032 }
qining4f4bb812016-04-03 23:55:17 -04005033
5034 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5035 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005036 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005037 exit(1);
5038 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005039}
5040
John Kessenich140f3df2015-06-26 16:58:36 -06005041// Use 'consts' as the flattened glslang source of scalar constants to recursively
5042// build the aggregate SPIR-V constant.
5043//
5044// If there are not enough elements present in 'consts', 0 will be substituted;
5045// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5046//
qining08408382016-03-21 09:51:37 -04005047spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005048{
5049 // vector of constants for SPIR-V
5050 std::vector<spv::Id> spvConsts;
5051
5052 // Type is used for struct and array constants
5053 spv::Id typeId = convertGlslangToSpvType(glslangType);
5054
5055 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005056 glslang::TType elementType(glslangType, 0);
5057 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005058 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005059 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005060 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005061 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005062 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005063 } else if (glslangType.getStruct()) {
5064 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5065 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005066 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005067 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005068 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5069 bool zero = nextConst >= consts.size();
5070 switch (glslangType.getBasicType()) {
5071 case glslang::EbtInt:
5072 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5073 break;
5074 case glslang::EbtUint:
5075 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5076 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005077 case glslang::EbtInt64:
5078 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5079 break;
5080 case glslang::EbtUint64:
5081 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5082 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005083 case glslang::EbtFloat:
5084 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5085 break;
5086 case glslang::EbtDouble:
5087 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5088 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005089#ifdef AMD_EXTENSIONS
5090 case glslang::EbtFloat16:
5091 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5092 break;
5093#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005094 case glslang::EbtBool:
5095 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5096 break;
5097 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005098 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005099 break;
5100 }
5101 ++nextConst;
5102 }
5103 } else {
5104 // we have a non-aggregate (scalar) constant
5105 bool zero = nextConst >= consts.size();
5106 spv::Id scalar = 0;
5107 switch (glslangType.getBasicType()) {
5108 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005109 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005110 break;
5111 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005112 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005113 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005114 case glslang::EbtInt64:
5115 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5116 break;
5117 case glslang::EbtUint64:
5118 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5119 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005120 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005121 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005122 break;
5123 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005124 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005125 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005126#ifdef AMD_EXTENSIONS
5127 case glslang::EbtFloat16:
5128 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5129 break;
5130#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005131 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005132 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005133 break;
5134 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005135 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005136 break;
5137 }
5138 ++nextConst;
5139 return scalar;
5140 }
5141
5142 return builder.makeCompositeConstant(typeId, spvConsts);
5143}
5144
John Kessenich7c1aa102015-10-15 13:29:11 -06005145// Return true if the node is a constant or symbol whose reading has no
5146// non-trivial observable cost or effect.
5147bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5148{
5149 // don't know what this is
5150 if (node == nullptr)
5151 return false;
5152
5153 // a constant is safe
5154 if (node->getAsConstantUnion() != nullptr)
5155 return true;
5156
5157 // not a symbol means non-trivial
5158 if (node->getAsSymbolNode() == nullptr)
5159 return false;
5160
5161 // a symbol, depends on what's being read
5162 switch (node->getType().getQualifier().storage) {
5163 case glslang::EvqTemporary:
5164 case glslang::EvqGlobal:
5165 case glslang::EvqIn:
5166 case glslang::EvqInOut:
5167 case glslang::EvqConst:
5168 case glslang::EvqConstReadOnly:
5169 case glslang::EvqUniform:
5170 return true;
5171 default:
5172 return false;
5173 }
qining25262b32016-05-06 17:25:16 -04005174}
John Kessenich7c1aa102015-10-15 13:29:11 -06005175
5176// A node is trivial if it is a single operation with no side effects.
5177// Error on the side of saying non-trivial.
5178// Return true if trivial.
5179bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5180{
5181 if (node == nullptr)
5182 return false;
5183
5184 // symbols and constants are trivial
5185 if (isTrivialLeaf(node))
5186 return true;
5187
5188 // otherwise, it needs to be a simple operation or one or two leaf nodes
5189
5190 // not a simple operation
5191 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5192 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5193 if (binaryNode == nullptr && unaryNode == nullptr)
5194 return false;
5195
5196 // not on leaf nodes
5197 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5198 return false;
5199
5200 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5201 return false;
5202 }
5203
5204 switch (node->getAsOperator()->getOp()) {
5205 case glslang::EOpLogicalNot:
5206 case glslang::EOpConvIntToBool:
5207 case glslang::EOpConvUintToBool:
5208 case glslang::EOpConvFloatToBool:
5209 case glslang::EOpConvDoubleToBool:
5210 case glslang::EOpEqual:
5211 case glslang::EOpNotEqual:
5212 case glslang::EOpLessThan:
5213 case glslang::EOpGreaterThan:
5214 case glslang::EOpLessThanEqual:
5215 case glslang::EOpGreaterThanEqual:
5216 case glslang::EOpIndexDirect:
5217 case glslang::EOpIndexDirectStruct:
5218 case glslang::EOpLogicalXor:
5219 case glslang::EOpAny:
5220 case glslang::EOpAll:
5221 return true;
5222 default:
5223 return false;
5224 }
5225}
5226
5227// Emit short-circuiting code, where 'right' is never evaluated unless
5228// the left side is true (for &&) or false (for ||).
5229spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5230{
5231 spv::Id boolTypeId = builder.makeBoolType();
5232
5233 // emit left operand
5234 builder.clearAccessChain();
5235 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005236 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005237
5238 // Operands to accumulate OpPhi operands
5239 std::vector<spv::Id> phiOperands;
5240 // accumulate left operand's phi information
5241 phiOperands.push_back(leftId);
5242 phiOperands.push_back(builder.getBuildPoint()->getId());
5243
5244 // Make the two kinds of operation symmetric with a "!"
5245 // || => emit "if (! left) result = right"
5246 // && => emit "if ( left) result = right"
5247 //
5248 // TODO: this runtime "not" for || could be avoided by adding functionality
5249 // to 'builder' to have an "else" without an "then"
5250 if (op == glslang::EOpLogicalOr)
5251 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5252
5253 // make an "if" based on the left value
5254 spv::Builder::If ifBuilder(leftId, builder);
5255
5256 // emit right operand as the "then" part of the "if"
5257 builder.clearAccessChain();
5258 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005259 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005260
5261 // accumulate left operand's phi information
5262 phiOperands.push_back(rightId);
5263 phiOperands.push_back(builder.getBuildPoint()->getId());
5264
5265 // finish the "if"
5266 ifBuilder.makeEndIf();
5267
5268 // phi together the two results
5269 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5270}
5271
Rex Xu9d93a232016-05-05 12:30:44 +08005272// Return type Id of the imported set of extended instructions corresponds to the name.
5273// Import this set if it has not been imported yet.
5274spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5275{
5276 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5277 return extBuiltinMap[name];
5278 else {
Rex Xu51596642016-09-21 18:56:12 +08005279 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005280 spv::Id extBuiltins = builder.import(name);
5281 extBuiltinMap[name] = extBuiltins;
5282 return extBuiltins;
5283 }
5284}
5285
John Kessenich140f3df2015-06-26 16:58:36 -06005286}; // end anonymous namespace
5287
5288namespace glslang {
5289
John Kessenich68d78fd2015-07-12 19:28:10 -06005290void GetSpirvVersion(std::string& version)
5291{
John Kessenich9e55f632015-07-15 10:03:39 -06005292 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005293 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005294 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005295 version = buf;
5296}
5297
John Kessenich140f3df2015-06-26 16:58:36 -06005298// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005299void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005300{
5301 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005302 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005303 for (int i = 0; i < (int)spirv.size(); ++i) {
5304 unsigned int word = spirv[i];
5305 out.write((const char*)&word, 4);
5306 }
5307 out.close();
5308}
5309
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005310// Write SPIR-V out to a text file with 32-bit hexadecimal words
5311void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5312{
5313 std::ofstream out;
5314 out.open(baseName, std::ios::binary | std::ios::out);
5315 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5316 const int WORDS_PER_LINE = 8;
5317 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5318 out << "\t";
5319 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5320 const unsigned int word = spirv[i + j];
5321 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5322 if (i + j + 1 < (int)spirv.size()) {
5323 out << ",";
5324 }
5325 }
5326 out << std::endl;
5327 }
5328 out.close();
5329}
5330
John Kessenich140f3df2015-06-26 16:58:36 -06005331//
5332// Set up the glslang traversal
5333//
5334void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5335{
Lei Zhang17535f72016-05-04 15:55:59 -04005336 spv::SpvBuildLogger logger;
5337 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005338}
5339
Lei Zhang17535f72016-05-04 15:55:59 -04005340void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005341{
John Kessenich140f3df2015-06-26 16:58:36 -06005342 TIntermNode* root = intermediate.getTreeRoot();
5343
5344 if (root == 0)
5345 return;
5346
5347 glslang::GetThreadPoolAllocator().push();
5348
Lei Zhang17535f72016-05-04 15:55:59 -04005349 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005350 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005351 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005352 it.dumpSpv(spirv);
5353
5354 glslang::GetThreadPoolAllocator().pop();
5355}
5356
5357}; // end namespace glslang