blob: 11d8e315081bd3e9372a4a56baab96b1f59319b8 [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 Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
150 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600151 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600152 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
153 glslang::TLayoutPacking, const glslang::TQualifier&);
154 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
155 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700156 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700157 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800158 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600159 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700160 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700161 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
162 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700163 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
164 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100165 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600166
John Kessenich6fccb3c2016-09-19 16:01:41 -0600167 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600168 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600169 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void makeFunctions(const glslang::TIntermSequence&);
171 void makeGlobalInitializers(const glslang::TIntermSequence&);
172 void visitFunctions(const glslang::TIntermSequence&);
173 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600175 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
176 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600177 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
178
John Kessenichead86222018-03-28 18:01:20 -0600179 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
180 glslang::TBasicType typeProxy, bool reduceComparison = true);
181 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
182 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600188 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800190 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 +0800191 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800192 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600194 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 +0800195 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700197#ifdef NV_EXTENSIONS
198 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
199#endif
qining08408382016-03-21 09:51:37 -0400200 spv::Id createSpvConstant(const glslang::TIntermTyped&);
201 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600202 bool isTrivialLeaf(const glslang::TIntermTyped* node);
203 bool isTrivial(const glslang::TIntermTyped* node);
204 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800206 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700208 void addPre13Extension(const char* ext)
209 {
210 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
211 builder.addExtension(ext);
212 }
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 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 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
229 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800230 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600231
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600233 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700235 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
237 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700239 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
279 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
280 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
281#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600282 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700283 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600284 return spv::ExecutionModelFragment;
285 }
286}
287
John Kessenich140f3df2015-06-26 16:58:36 -0600288// Translate glslang sampler type to SPIR-V dimensionality.
289spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
290{
291 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700292 case glslang::Esd1D: return spv::Dim1D;
293 case glslang::Esd2D: return spv::Dim2D;
294 case glslang::Esd3D: return spv::Dim3D;
295 case glslang::EsdCube: return spv::DimCube;
296 case glslang::EsdRect: return spv::DimRect;
297 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700298 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600299 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700300 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600301 return spv::Dim2D;
302 }
303}
304
John Kessenichf6640762016-08-01 19:44:00 -0600305// Translate glslang precision to SPIR-V precision decorations.
306spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600307{
John Kessenichf6640762016-08-01 19:44:00 -0600308 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700309 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600310 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600311 default:
312 return spv::NoPrecision;
313 }
314}
315
John Kessenichf6640762016-08-01 19:44:00 -0600316// Translate glslang type to SPIR-V precision decorations.
317spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
318{
319 return TranslatePrecisionDecoration(type.getQualifier().precision);
320}
321
John Kessenich140f3df2015-06-26 16:58:36 -0600322// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600323spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600324{
325 if (type.getBasicType() == glslang::EbtBlock) {
326 switch (type.getQualifier().storage) {
327 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600328 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600329 case glslang::EvqVaryingIn: return spv::DecorationBlock;
330 case glslang::EvqVaryingOut: return spv::DecorationBlock;
331 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700332 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600333 break;
334 }
335 }
336
John Kessenich4016e382016-07-15 11:53:56 -0600337 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600338}
339
Rex Xu1da878f2016-02-21 20:59:01 +0800340// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500341void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800342{
Jeff Bolz36831c92018-09-05 10:11:41 -0500343 if (!useVulkanMemoryModel) {
344 if (qualifier.coherent)
345 memory.push_back(spv::DecorationCoherent);
346 if (qualifier.volatil) {
347 memory.push_back(spv::DecorationVolatile);
348 memory.push_back(spv::DecorationCoherent);
349 }
John Kessenich14b85d32018-06-04 15:36:03 -0600350 }
Rex Xu1da878f2016-02-21 20:59:01 +0800351 if (qualifier.restrict)
352 memory.push_back(spv::DecorationRestrict);
353 if (qualifier.readonly)
354 memory.push_back(spv::DecorationNonWritable);
355 if (qualifier.writeonly)
356 memory.push_back(spv::DecorationNonReadable);
357}
358
John Kessenich140f3df2015-06-26 16:58:36 -0600359// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700360spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600361{
362 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700363 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600364 case glslang::ElmRowMajor:
365 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700366 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700368 default:
369 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600370 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 }
372 } else {
373 switch (type.getBasicType()) {
374 default:
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 break;
377 case glslang::EbtBlock:
378 switch (type.getQualifier().storage) {
379 case glslang::EvqUniform:
380 case glslang::EvqBuffer:
381 switch (type.getQualifier().layoutPacking) {
382 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600383 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
384 default:
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600386 }
387 case glslang::EvqVaryingIn:
388 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700389 if (type.getQualifier().isTaskMemory()) {
390 switch (type.getQualifier().layoutPacking) {
391 case glslang::ElpShared: return spv::DecorationGLSLShared;
392 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
393 default: break;
394 }
395 } else {
396 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
397 }
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700400 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600402 }
403 }
404 }
405}
406
407// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700409// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800410spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600411{
Rex Xubbceed72016-05-21 09:40:44 +0800412 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700413 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800415 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700416 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700417 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800419#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800420 else if (qualifier.explicitInterp) {
421 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800422 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800423 }
Rex Xu9d93a232016-05-05 12:30:44 +0800424#endif
Rex Xubbceed72016-05-21 09:40:44 +0800425 else
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800427}
428
429// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600430// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800431// should be applied.
432spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
433{
434 if (qualifier.patch)
435 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700436 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600437 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700438 else if (qualifier.sample) {
439 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600440 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700441 } else
John Kessenich4016e382016-07-15 11:53:56 -0600442 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600443}
444
John Kessenich92187592016-02-01 13:45:25 -0700445// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700446spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700448 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600449 return spv::DecorationInvariant;
450 else
John Kessenich4016e382016-07-15 11:53:56 -0600451 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600452}
453
qining9220dbb2016-05-04 17:34:38 -0400454// If glslang type is noContraction, return SPIR-V NoContraction decoration.
455spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
456{
457 if (qualifier.noContraction)
458 return spv::DecorationNoContraction;
459 else
John Kessenich4016e382016-07-15 11:53:56 -0600460 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400461}
462
John Kessenich5611c6d2018-04-05 11:25:02 -0600463// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
464spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
465{
466 if (qualifier.isNonUniform()) {
467 builder.addExtension("SPV_EXT_descriptor_indexing");
468 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
469 return spv::DecorationNonUniformEXT;
470 } else
471 return spv::DecorationMax;
472}
473
Jeff Bolz36831c92018-09-05 10:11:41 -0500474spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
475{
476 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
477 return spv::MemoryAccessMaskNone;
478 }
479 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
480 if (coherentFlags.volatil ||
481 coherentFlags.coherent ||
482 coherentFlags.devicecoherent ||
483 coherentFlags.queuefamilycoherent ||
484 coherentFlags.workgroupcoherent ||
485 coherentFlags.subgroupcoherent) {
486 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
487 spv::MemoryAccessMakePointerVisibleKHRMask;
488 }
489 if (coherentFlags.nonprivate) {
490 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
491 }
492 if (coherentFlags.volatil) {
493 mask = mask | spv::MemoryAccessVolatileMask;
494 }
495 if (mask != spv::MemoryAccessMaskNone) {
496 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
497 }
498 return mask;
499}
500
501spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
502{
503 if (!glslangIntermediate->usingVulkanMemoryModel()) {
504 return spv::ImageOperandsMaskNone;
505 }
506 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
507 if (coherentFlags.volatil ||
508 coherentFlags.coherent ||
509 coherentFlags.devicecoherent ||
510 coherentFlags.queuefamilycoherent ||
511 coherentFlags.workgroupcoherent ||
512 coherentFlags.subgroupcoherent) {
513 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
514 spv::ImageOperandsMakeTexelVisibleKHRMask;
515 }
516 if (coherentFlags.nonprivate) {
517 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
518 }
519 if (coherentFlags.volatil) {
520 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
521 }
522 if (mask != spv::ImageOperandsMaskNone) {
523 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
524 }
525 return mask;
526}
527
528spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
529{
530 spv::Builder::AccessChain::CoherentFlags flags;
531 flags.coherent = type.getQualifier().coherent;
532 flags.devicecoherent = type.getQualifier().devicecoherent;
533 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
534 // shared variables are implicitly workgroupcoherent in GLSL.
535 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
536 type.getQualifier().storage == glslang::EvqShared;
537 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
538 // *coherent variables are implicitly nonprivate in GLSL
539 flags.nonprivate = type.getQualifier().nonprivate ||
540 type.getQualifier().subgroupcoherent ||
541 type.getQualifier().workgroupcoherent ||
542 type.getQualifier().queuefamilycoherent ||
543 type.getQualifier().devicecoherent ||
544 type.getQualifier().coherent;
545 flags.volatil = type.getQualifier().volatil;
546 flags.isImage = type.getBasicType() == glslang::EbtSampler;
547 return flags;
548}
549
550spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
551{
552 spv::Scope scope;
553 if (coherentFlags.coherent) {
554 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
555 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
556 } else if (coherentFlags.devicecoherent) {
557 scope = spv::ScopeDevice;
558 } else if (coherentFlags.queuefamilycoherent) {
559 scope = spv::ScopeQueueFamilyKHR;
560 } else if (coherentFlags.workgroupcoherent) {
561 scope = spv::ScopeWorkgroup;
562 } else if (coherentFlags.subgroupcoherent) {
563 scope = spv::ScopeSubgroup;
564 } else {
565 scope = spv::ScopeMax;
566 }
567 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
568 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
569 }
570 return scope;
571}
572
David Netoa901ffe2016-06-08 14:11:40 +0100573// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
574// associated capabilities when required. For some built-in variables, a capability
575// is generated only when using the variable in an executable instruction, but not when
576// just declaring a struct member variable with it. This is true for PointSize,
577// ClipDistance, and CullDistance.
578spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600579{
580 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700581 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600582 // Defer adding the capability until the built-in is actually used.
583 if (! memberDeclaration) {
584 switch (glslangIntermediate->getStage()) {
585 case EShLangGeometry:
586 builder.addCapability(spv::CapabilityGeometryPointSize);
587 break;
588 case EShLangTessControl:
589 case EShLangTessEvaluation:
590 builder.addCapability(spv::CapabilityTessellationPointSize);
591 break;
592 default:
593 break;
594 }
John Kessenich92187592016-02-01 13:45:25 -0700595 }
596 return spv::BuiltInPointSize;
597
John Kessenichebb50532016-05-16 19:22:05 -0600598 // These *Distance capabilities logically belong here, but if the member is declared and
599 // then never used, consumers of SPIR-V prefer the capability not be declared.
600 // They are now generated when used, rather than here when declared.
601 // Potentially, the specification should be more clear what the minimum
602 // use needed is to trigger the capability.
603 //
John Kessenich92187592016-02-01 13:45:25 -0700604 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100605 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800606 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700607 return spv::BuiltInClipDistance;
608
609 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100610 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800611 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700612 return spv::BuiltInCullDistance;
613
614 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600615 builder.addCapability(spv::CapabilityMultiViewport);
616 if (glslangIntermediate->getStage() == EShLangVertex ||
617 glslangIntermediate->getStage() == EShLangTessControl ||
618 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800619
John Kessenichba6a3c22017-09-13 13:22:50 -0600620 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
621 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800622 }
John Kessenich92187592016-02-01 13:45:25 -0700623 return spv::BuiltInViewportIndex;
624
John Kessenich5e801132016-02-15 11:09:46 -0700625 case glslang::EbvSampleId:
626 builder.addCapability(spv::CapabilitySampleRateShading);
627 return spv::BuiltInSampleId;
628
629 case glslang::EbvSamplePosition:
630 builder.addCapability(spv::CapabilitySampleRateShading);
631 return spv::BuiltInSamplePosition;
632
633 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700634 return spv::BuiltInSampleMask;
635
John Kessenich78a45572016-07-08 14:05:15 -0600636 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700637#ifdef NV_EXTENSIONS
638 if (glslangIntermediate->getStage() == EShLangMeshNV) {
639 return spv::BuiltInLayer;
640 }
641#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addCapability(spv::CapabilityGeometry);
643 if (glslangIntermediate->getStage() == EShLangVertex ||
644 glslangIntermediate->getStage() == EShLangTessControl ||
645 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800646
John Kessenichba6a3c22017-09-13 13:22:50 -0600647 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
648 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800649 }
John Kessenich78a45572016-07-08 14:05:15 -0600650 return spv::BuiltInLayer;
651
John Kessenich140f3df2015-06-26 16:58:36 -0600652 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600653 case glslang::EbvVertexId: return spv::BuiltInVertexId;
654 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700655 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
656 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800657
John Kessenichda581a22015-10-14 14:10:30 -0600658 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700659 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800660 builder.addCapability(spv::CapabilityDrawParameters);
661 return spv::BuiltInBaseVertex;
662
John Kessenichda581a22015-10-14 14:10:30 -0600663 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700664 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800665 builder.addCapability(spv::CapabilityDrawParameters);
666 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200667
John Kessenichda581a22015-10-14 14:10:30 -0600668 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700669 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800670 builder.addCapability(spv::CapabilityDrawParameters);
671 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200672
673 case glslang::EbvPrimitiveId:
674 if (glslangIntermediate->getStage() == EShLangFragment)
675 builder.addCapability(spv::CapabilityGeometry);
676 return spv::BuiltInPrimitiveId;
677
Rex Xu37cdcee2017-06-29 17:46:34 +0800678 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800679 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
680 builder.addCapability(spv::CapabilityStencilExportEXT);
681 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800682
John Kessenich140f3df2015-06-26 16:58:36 -0600683 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600684 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
685 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
686 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
687 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
688 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
689 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
690 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600691 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
692 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
693 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
694 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
695 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
696 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
697 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
698 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800699
Rex Xu574ab042016-04-14 16:53:07 +0800700 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800701 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800702 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
703 return spv::BuiltInSubgroupSize;
704
Rex Xu574ab042016-04-14 16:53:07 +0800705 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800706 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800707 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
708 return spv::BuiltInSubgroupLocalInvocationId;
709
Rex Xu574ab042016-04-14 16:53:07 +0800710 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800711 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
712 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
713 return spv::BuiltInSubgroupEqMaskKHR;
714
Rex Xu574ab042016-04-14 16:53:07 +0800715 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800716 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
717 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
718 return spv::BuiltInSubgroupGeMaskKHR;
719
Rex Xu574ab042016-04-14 16:53:07 +0800720 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800721 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
722 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
723 return spv::BuiltInSubgroupGtMaskKHR;
724
Rex Xu574ab042016-04-14 16:53:07 +0800725 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800726 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
727 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
728 return spv::BuiltInSubgroupLeMaskKHR;
729
Rex Xu574ab042016-04-14 16:53:07 +0800730 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800731 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
732 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
733 return spv::BuiltInSubgroupLtMaskKHR;
734
John Kessenich66011cb2018-03-06 16:12:04 -0700735 case glslang::EbvNumSubgroups:
736 builder.addCapability(spv::CapabilityGroupNonUniform);
737 return spv::BuiltInNumSubgroups;
738
739 case glslang::EbvSubgroupID:
740 builder.addCapability(spv::CapabilityGroupNonUniform);
741 return spv::BuiltInSubgroupId;
742
743 case glslang::EbvSubgroupSize2:
744 builder.addCapability(spv::CapabilityGroupNonUniform);
745 return spv::BuiltInSubgroupSize;
746
747 case glslang::EbvSubgroupInvocation2:
748 builder.addCapability(spv::CapabilityGroupNonUniform);
749 return spv::BuiltInSubgroupLocalInvocationId;
750
751 case glslang::EbvSubgroupEqMask2:
752 builder.addCapability(spv::CapabilityGroupNonUniform);
753 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
754 return spv::BuiltInSubgroupEqMask;
755
756 case glslang::EbvSubgroupGeMask2:
757 builder.addCapability(spv::CapabilityGroupNonUniform);
758 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
759 return spv::BuiltInSubgroupGeMask;
760
761 case glslang::EbvSubgroupGtMask2:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
764 return spv::BuiltInSubgroupGtMask;
765
766 case glslang::EbvSubgroupLeMask2:
767 builder.addCapability(spv::CapabilityGroupNonUniform);
768 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
769 return spv::BuiltInSubgroupLeMask;
770
771 case glslang::EbvSubgroupLtMask2:
772 builder.addCapability(spv::CapabilityGroupNonUniform);
773 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
774 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800775#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800776 case glslang::EbvBaryCoordNoPersp:
777 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
778 return spv::BuiltInBaryCoordNoPerspAMD;
779
780 case glslang::EbvBaryCoordNoPerspCentroid:
781 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
782 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
783
784 case glslang::EbvBaryCoordNoPerspSample:
785 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
786 return spv::BuiltInBaryCoordNoPerspSampleAMD;
787
788 case glslang::EbvBaryCoordSmooth:
789 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
790 return spv::BuiltInBaryCoordSmoothAMD;
791
792 case glslang::EbvBaryCoordSmoothCentroid:
793 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
794 return spv::BuiltInBaryCoordSmoothCentroidAMD;
795
796 case glslang::EbvBaryCoordSmoothSample:
797 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
798 return spv::BuiltInBaryCoordSmoothSampleAMD;
799
800 case glslang::EbvBaryCoordPullModel:
801 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
802 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800803#endif
chaoc771d89f2017-01-13 01:10:53 -0800804
John Kessenich6c8aaac2017-02-27 01:20:51 -0700805 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700806 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700807 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700808 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700809
810 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700811 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700812 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700813 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700814
chaoc771d89f2017-01-13 01:10:53 -0800815#ifdef NV_EXTENSIONS
816 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800817 if (!memberDeclaration) {
818 builder.addExtension(spv::E_SPV_NV_viewport_array2);
819 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
820 }
chaoc771d89f2017-01-13 01:10:53 -0800821 return spv::BuiltInViewportMaskNV;
822 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800823 if (!memberDeclaration) {
824 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
825 builder.addCapability(spv::CapabilityShaderStereoViewNV);
826 }
chaoc771d89f2017-01-13 01:10:53 -0800827 return spv::BuiltInSecondaryPositionNV;
828 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800829 if (!memberDeclaration) {
830 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
831 builder.addCapability(spv::CapabilityShaderStereoViewNV);
832 }
chaoc771d89f2017-01-13 01:10:53 -0800833 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800834 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800835 if (!memberDeclaration) {
836 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
837 builder.addCapability(spv::CapabilityPerViewAttributesNV);
838 }
chaocdf3956c2017-02-14 14:52:34 -0800839 return spv::BuiltInPositionPerViewNV;
840 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800841 if (!memberDeclaration) {
842 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
843 builder.addCapability(spv::CapabilityPerViewAttributesNV);
844 }
chaocdf3956c2017-02-14 14:52:34 -0800845 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700846 case glslang::EbvFragFullyCoveredNV:
847 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
848 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
849 return spv::BuiltInFullyCoveredEXT;
Chao Chen9eada4b2018-09-19 11:39:56 -0700850 case glslang::EbvBaryCoordNV:
851 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
852 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
853 return spv::BuiltInBaryCoordNV;
854 case glslang::EbvBaryCoordNoPerspNV:
855 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
856 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
857 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700858 case glslang::EbvTaskCountNV:
859 return spv::BuiltInTaskCountNV;
860 case glslang::EbvPrimitiveCountNV:
861 return spv::BuiltInPrimitiveCountNV;
862 case glslang::EbvPrimitiveIndicesNV:
863 return spv::BuiltInPrimitiveIndicesNV;
864 case glslang::EbvClipDistancePerViewNV:
865 return spv::BuiltInClipDistancePerViewNV;
866 case glslang::EbvCullDistancePerViewNV:
867 return spv::BuiltInCullDistancePerViewNV;
868 case glslang::EbvLayerPerViewNV:
869 return spv::BuiltInLayerPerViewNV;
870 case glslang::EbvMeshViewCountNV:
871 return spv::BuiltInMeshViewCountNV;
872 case glslang::EbvMeshViewIndicesNV:
873 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800874#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800875 default:
876 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600877 }
878}
879
Rex Xufc618912015-09-09 16:42:49 +0800880// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700881spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800882{
883 assert(type.getBasicType() == glslang::EbtSampler);
884
John Kessenich5d0fa972016-02-15 11:57:00 -0700885 // Check for capabilities
886 switch (type.getQualifier().layoutFormat) {
887 case glslang::ElfRg32f:
888 case glslang::ElfRg16f:
889 case glslang::ElfR11fG11fB10f:
890 case glslang::ElfR16f:
891 case glslang::ElfRgba16:
892 case glslang::ElfRgb10A2:
893 case glslang::ElfRg16:
894 case glslang::ElfRg8:
895 case glslang::ElfR16:
896 case glslang::ElfR8:
897 case glslang::ElfRgba16Snorm:
898 case glslang::ElfRg16Snorm:
899 case glslang::ElfRg8Snorm:
900 case glslang::ElfR16Snorm:
901 case glslang::ElfR8Snorm:
902
903 case glslang::ElfRg32i:
904 case glslang::ElfRg16i:
905 case glslang::ElfRg8i:
906 case glslang::ElfR16i:
907 case glslang::ElfR8i:
908
909 case glslang::ElfRgb10a2ui:
910 case glslang::ElfRg32ui:
911 case glslang::ElfRg16ui:
912 case glslang::ElfRg8ui:
913 case glslang::ElfR16ui:
914 case glslang::ElfR8ui:
915 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
916 break;
917
918 default:
919 break;
920 }
921
922 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800923 switch (type.getQualifier().layoutFormat) {
924 case glslang::ElfNone: return spv::ImageFormatUnknown;
925 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
926 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
927 case glslang::ElfR32f: return spv::ImageFormatR32f;
928 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
929 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
930 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
931 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
932 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
933 case glslang::ElfR16f: return spv::ImageFormatR16f;
934 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
935 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
936 case glslang::ElfRg16: return spv::ImageFormatRg16;
937 case glslang::ElfRg8: return spv::ImageFormatRg8;
938 case glslang::ElfR16: return spv::ImageFormatR16;
939 case glslang::ElfR8: return spv::ImageFormatR8;
940 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
941 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
942 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
943 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
944 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
945 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
946 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
947 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
948 case glslang::ElfR32i: return spv::ImageFormatR32i;
949 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
950 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
951 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
952 case glslang::ElfR16i: return spv::ImageFormatR16i;
953 case glslang::ElfR8i: return spv::ImageFormatR8i;
954 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
955 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
956 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
957 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
958 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
959 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
960 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
961 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
962 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
963 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600964 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800965 }
966}
967
John Kesseniche18fd202018-01-30 11:01:39 -0700968spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800969{
John Kesseniche18fd202018-01-30 11:01:39 -0700970 if (selectionNode.getFlatten())
971 return spv::SelectionControlFlattenMask;
972 if (selectionNode.getDontFlatten())
973 return spv::SelectionControlDontFlattenMask;
974 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800975}
976
John Kesseniche18fd202018-01-30 11:01:39 -0700977spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600978{
John Kesseniche18fd202018-01-30 11:01:39 -0700979 if (switchNode.getFlatten())
980 return spv::SelectionControlFlattenMask;
981 if (switchNode.getDontFlatten())
982 return spv::SelectionControlDontFlattenMask;
983 return spv::SelectionControlMaskNone;
984}
985
John Kessenicha2858d92018-01-31 08:11:18 -0700986// return a non-0 dependency if the dependency argument must be set
987spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
988 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700989{
990 spv::LoopControlMask control = spv::LoopControlMaskNone;
991
992 if (loopNode.getDontUnroll())
993 control = control | spv::LoopControlDontUnrollMask;
994 if (loopNode.getUnroll())
995 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700996 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700997 control = control | spv::LoopControlDependencyInfiniteMask;
998 else if (loopNode.getLoopDependency() > 0) {
999 control = control | spv::LoopControlDependencyLengthMask;
1000 dependencyLength = loopNode.getLoopDependency();
1001 }
John Kesseniche18fd202018-01-30 11:01:39 -07001002
1003 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001004}
1005
John Kessenicha5c5fb62017-05-05 05:09:58 -06001006// Translate glslang type to SPIR-V storage class.
1007spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1008{
1009 if (type.getQualifier().isPipeInput())
1010 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001011 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001012 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001013
1014 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1015 type.getQualifier().storage == glslang::EvqUniform) {
1016 if (type.getBasicType() == glslang::EbtAtomicUint)
1017 return spv::StorageClassAtomicCounter;
1018 if (type.containsOpaque())
1019 return spv::StorageClassUniformConstant;
1020 }
1021
1022 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001023 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001024 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001025 }
1026
1027 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001028 if (type.getQualifier().layoutPushConstant)
1029 return spv::StorageClassPushConstant;
1030 if (type.getBasicType() == glslang::EbtBlock)
1031 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001032 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001033 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001034
1035 switch (type.getQualifier().storage) {
1036 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1037 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1038 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1039 case glslang::EvqTemporary: return spv::StorageClassFunction;
1040 default:
1041 assert(0);
1042 break;
1043 }
1044
1045 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001046}
1047
John Kessenich5611c6d2018-04-05 11:25:02 -06001048// Add capabilities pertaining to how an array is indexed.
1049void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1050 const glslang::TType& indexType)
1051{
1052 if (indexType.getQualifier().isNonUniform()) {
1053 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001054 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001055 if (baseType.getBasicType() == glslang::EbtSampler) {
1056 if (baseType.getQualifier().hasAttachment())
1057 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1058 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1059 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1060 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1061 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1062 else if (baseType.isImage())
1063 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1064 else if (baseType.isTexture())
1065 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1066 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1067 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1068 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1069 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1070 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1071 }
1072 } else {
1073 // assume a dynamically uniform index
1074 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001075 if (baseType.getQualifier().hasAttachment()) {
1076 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001077 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001078 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1079 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001080 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001081 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1082 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001083 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001084 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001085 }
1086 }
1087}
1088
qining25262b32016-05-06 17:25:16 -04001089// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001090// descriptor set.
1091bool IsDescriptorResource(const glslang::TType& type)
1092{
John Kessenichf7497e22016-03-08 21:36:22 -07001093 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001094 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -07001095 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001096
1097 // non block...
1098 // basically samplerXXX/subpass/sampler/texture are all included
1099 // if they are the global-scope-class, not the function parameter
1100 // (or local, if they ever exist) class.
1101 if (type.getBasicType() == glslang::EbtSampler)
1102 return type.getQualifier().isUniformOrBuffer();
1103
1104 // None of the above.
1105 return false;
1106}
1107
John Kesseniche0b6cad2015-12-24 10:30:13 -07001108void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1109{
1110 if (child.layoutMatrix == glslang::ElmNone)
1111 child.layoutMatrix = parent.layoutMatrix;
1112
1113 if (parent.invariant)
1114 child.invariant = true;
1115 if (parent.nopersp)
1116 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001117#ifdef AMD_EXTENSIONS
1118 if (parent.explicitInterp)
1119 child.explicitInterp = true;
1120#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001121 if (parent.flat)
1122 child.flat = true;
1123 if (parent.centroid)
1124 child.centroid = true;
1125 if (parent.patch)
1126 child.patch = true;
1127 if (parent.sample)
1128 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001129 if (parent.coherent)
1130 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001131 if (parent.devicecoherent)
1132 child.devicecoherent = true;
1133 if (parent.queuefamilycoherent)
1134 child.queuefamilycoherent = true;
1135 if (parent.workgroupcoherent)
1136 child.workgroupcoherent = true;
1137 if (parent.subgroupcoherent)
1138 child.subgroupcoherent = true;
1139 if (parent.nonprivate)
1140 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001141 if (parent.volatil)
1142 child.volatil = true;
1143 if (parent.restrict)
1144 child.restrict = true;
1145 if (parent.readonly)
1146 child.readonly = true;
1147 if (parent.writeonly)
1148 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001149#ifdef NV_EXTENSIONS
1150 if (parent.perPrimitiveNV)
1151 child.perPrimitiveNV = true;
1152 if (parent.perViewNV)
1153 child.perViewNV = true;
1154 if (parent.perTaskNV)
1155 child.perTaskNV = true;
1156#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001157}
1158
John Kessenichf2b7f332016-09-01 17:05:23 -06001159bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001160{
John Kessenich7b9fa252016-01-21 18:56:57 -07001161 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001162 // - struct members might inherit from a struct declaration
1163 // (note that non-block structs don't explicitly inherit,
1164 // only implicitly, meaning no decoration involved)
1165 // - affect decorations on the struct members
1166 // (note smooth does not, and expecting something like volatile
1167 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001168 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001169 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001170}
1171
John Kessenich140f3df2015-06-26 16:58:36 -06001172//
1173// Implement the TGlslangToSpvTraverser class.
1174//
1175
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001176TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001177 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1178 : TIntermTraverser(true, false, true),
1179 options(options),
1180 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001181 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001182 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001183 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001184 glslangIntermediate(glslangIntermediate)
1185{
1186 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1187
1188 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001189 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1190 glslangIntermediate->getVersion());
1191
John Kessenich121853f2017-05-31 17:11:16 -06001192 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001193 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001194 builder.setSourceFile(glslangIntermediate->getSourceFile());
1195
1196 // Set the source shader's text. If for SPV version 1.0, include
1197 // a preamble in comments stating the OpModuleProcessed instructions.
1198 // Otherwise, emit those as actual instructions.
1199 std::string text;
1200 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1201 for (int p = 0; p < (int)processes.size(); ++p) {
1202 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1203 text.append("// OpModuleProcessed ");
1204 text.append(processes[p]);
1205 text.append("\n");
1206 } else
1207 builder.addModuleProcessed(processes[p]);
1208 }
1209 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1210 text.append("#line 1\n");
1211 text.append(glslangIntermediate->getSourceText());
1212 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001213 }
John Kessenich140f3df2015-06-26 16:58:36 -06001214 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001215 if (glslangIntermediate->usingVulkanMemoryModel()) {
1216 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1217 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1218 } else {
1219 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1220 }
John Kessenicheee9d532016-09-19 18:09:30 -06001221 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1222 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
1224 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001225 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1226 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001227 builder.addSourceExtension(it->c_str());
1228
1229 // Add the top-level modes for this shader.
1230
John Kessenich92187592016-02-01 13:45:25 -07001231 if (glslangIntermediate->getXfbMode()) {
1232 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001233 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001234 }
John Kessenich140f3df2015-06-26 16:58:36 -06001235
1236 unsigned int mode;
1237 switch (glslangIntermediate->getStage()) {
1238 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001239 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001240 break;
1241
steve-lunarge7412492017-03-23 11:56:07 -06001242 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001243 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001244 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001245
steve-lunarge7412492017-03-23 11:56:07 -06001246 glslang::TLayoutGeometry primitive;
1247
1248 if (glslangIntermediate->getStage() == EShLangTessControl) {
1249 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1250 primitive = glslangIntermediate->getOutputPrimitive();
1251 } else {
1252 primitive = glslangIntermediate->getInputPrimitive();
1253 }
1254
1255 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001256 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1257 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1258 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001259 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001260 }
John Kessenich4016e382016-07-15 11:53:56 -06001261 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001262 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1263
John Kesseniche6903322015-10-13 16:29:02 -06001264 switch (glslangIntermediate->getVertexSpacing()) {
1265 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1266 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1267 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001268 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001269 }
John Kessenich4016e382016-07-15 11:53:56 -06001270 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001271 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1272
1273 switch (glslangIntermediate->getVertexOrder()) {
1274 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1275 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001276 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001277 }
John Kessenich4016e382016-07-15 11:53:56 -06001278 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001279 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1280
1281 if (glslangIntermediate->getPointMode())
1282 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001283 break;
1284
1285 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001286 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001287 switch (glslangIntermediate->getInputPrimitive()) {
1288 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1289 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1290 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001291 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001292 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001293 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001294 }
John Kessenich4016e382016-07-15 11:53:56 -06001295 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001296 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001297
John Kessenich140f3df2015-06-26 16:58:36 -06001298 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1299
1300 switch (glslangIntermediate->getOutputPrimitive()) {
1301 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1302 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1303 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001304 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001305 }
John Kessenich4016e382016-07-15 11:53:56 -06001306 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1308 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1309 break;
1310
1311 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001312 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001313 if (glslangIntermediate->getPixelCenterInteger())
1314 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001315
John Kessenich140f3df2015-06-26 16:58:36 -06001316 if (glslangIntermediate->getOriginUpperLeft())
1317 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001318 else
1319 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001320
1321 if (glslangIntermediate->getEarlyFragmentTests())
1322 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1323
chaocc1204522017-06-30 17:14:30 -07001324 if (glslangIntermediate->getPostDepthCoverage()) {
1325 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1326 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1327 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1328 }
1329
John Kesseniche6903322015-10-13 16:29:02 -06001330 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001331 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1332 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001333 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001334 }
John Kessenich4016e382016-07-15 11:53:56 -06001335 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001336 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1337
1338 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1339 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001340 break;
1341
1342 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001343 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001344 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1345 glslangIntermediate->getLocalSize(1),
1346 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001347#ifdef NV_EXTENSIONS
1348 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1349 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1350 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1351 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1352 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1353 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1354 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1355 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1356 }
1357#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001358 break;
1359
Chao Chen3c366992018-09-19 11:41:59 -07001360#ifdef NV_EXTENSIONS
1361 case EShLangTaskNV:
1362 case EShLangMeshNV:
1363 builder.addCapability(spv::CapabilityMeshShadingNV);
1364 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1365 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1366 glslangIntermediate->getLocalSize(1),
1367 glslangIntermediate->getLocalSize(2));
1368 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1369 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1370 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1371
1372 switch (glslangIntermediate->getOutputPrimitive()) {
1373 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1374 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1375 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1376 default: mode = spv::ExecutionModeMax; break;
1377 }
1378 if (mode != spv::ExecutionModeMax)
1379 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1380 }
1381 break;
1382#endif
1383
John Kessenich140f3df2015-06-26 16:58:36 -06001384 default:
1385 break;
1386 }
John Kessenich140f3df2015-06-26 16:58:36 -06001387}
1388
John Kessenichfca82622016-11-26 13:23:20 -07001389// Finish creating SPV, after the traversal is complete.
1390void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001391{
John Kessenichf04c51b2018-08-03 15:56:12 -06001392 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001393 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001394 builder.setBuildPoint(shaderEntry->getLastBlock());
1395 builder.leaveFunction();
1396 }
1397
John Kessenich7ba63412015-12-20 17:37:07 -07001398 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001399 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1400 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001401
John Kessenichf04c51b2018-08-03 15:56:12 -06001402 // Add capabilities, extensions, remove unneeded decorations, etc.,
1403 // based on the resulting SPIR-V.
1404 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001405}
1406
John Kessenichfca82622016-11-26 13:23:20 -07001407// Write the SPV into 'out'.
1408void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001409{
John Kessenichfca82622016-11-26 13:23:20 -07001410 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001411}
1412
1413//
1414// Implement the traversal functions.
1415//
1416// Return true from interior nodes to have the external traversal
1417// continue on to children. Return false if children were
1418// already processed.
1419//
1420
1421//
qining25262b32016-05-06 17:25:16 -04001422// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001423// - uniform/input reads
1424// - output writes
1425// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1426// - something simple that degenerates into the last bullet
1427//
1428void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1429{
qining75d1d802016-04-06 14:42:01 -04001430 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1431 if (symbol->getType().getQualifier().isSpecConstant())
1432 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1433
John Kessenich140f3df2015-06-26 16:58:36 -06001434 // getSymbolId() will set up all the IO decorations on the first call.
1435 // Formal function parameters were mapped during makeFunctions().
1436 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001437
1438 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1439 if (builder.isPointer(id)) {
1440 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001441 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1442 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1443 iOSet.insert(id);
1444 }
John Kessenich7ba63412015-12-20 17:37:07 -07001445 }
1446
1447 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001448 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001449 // Prepare to generate code for the access
1450
1451 // L-value chains will be computed left to right. We're on the symbol now,
1452 // which is the left-most part of the access chain, so now is "clear" time,
1453 // followed by setting the base.
1454 builder.clearAccessChain();
1455
1456 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001457 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001458 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001459 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001460 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001461 // These are also pure R-values.
1462 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001463 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001464 builder.setAccessChainRValue(id);
1465 else
1466 builder.setAccessChainLValue(id);
1467 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001468
1469 // Process linkage-only nodes for any special additional interface work.
1470 if (linkageOnly) {
1471 if (glslangIntermediate->getHlslFunctionality1()) {
1472 // Map implicit counter buffers to their originating buffers, which should have been
1473 // seen by now, given earlier pruning of unused counters, and preservation of order
1474 // of declaration.
1475 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1476 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1477 // Save possible originating buffers for counter buffers, keyed by
1478 // making the potential counter-buffer name.
1479 std::string keyName = symbol->getName().c_str();
1480 keyName = glslangIntermediate->addCounterBufferName(keyName);
1481 counterOriginator[keyName] = symbol;
1482 } else {
1483 // Handle a counter buffer, by finding the saved originating buffer.
1484 std::string keyName = symbol->getName().c_str();
1485 auto it = counterOriginator.find(keyName);
1486 if (it != counterOriginator.end()) {
1487 id = getSymbolId(it->second);
1488 if (id != spv::NoResult) {
1489 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001490 if (counterId != spv::NoResult) {
1491 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001492 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001493 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001494 }
1495 }
1496 }
1497 }
1498 }
1499 }
John Kessenich140f3df2015-06-26 16:58:36 -06001500}
1501
1502bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1503{
John Kesseniche485c7a2017-05-31 18:50:53 -06001504 builder.setLine(node->getLoc().line);
1505
qining40887662016-04-03 22:20:42 -04001506 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1507 if (node->getType().getQualifier().isSpecConstant())
1508 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1509
John Kessenich140f3df2015-06-26 16:58:36 -06001510 // First, handle special cases
1511 switch (node->getOp()) {
1512 case glslang::EOpAssign:
1513 case glslang::EOpAddAssign:
1514 case glslang::EOpSubAssign:
1515 case glslang::EOpMulAssign:
1516 case glslang::EOpVectorTimesMatrixAssign:
1517 case glslang::EOpVectorTimesScalarAssign:
1518 case glslang::EOpMatrixTimesScalarAssign:
1519 case glslang::EOpMatrixTimesMatrixAssign:
1520 case glslang::EOpDivAssign:
1521 case glslang::EOpModAssign:
1522 case glslang::EOpAndAssign:
1523 case glslang::EOpInclusiveOrAssign:
1524 case glslang::EOpExclusiveOrAssign:
1525 case glslang::EOpLeftShiftAssign:
1526 case glslang::EOpRightShiftAssign:
1527 // A bin-op assign "a += b" means the same thing as "a = a + b"
1528 // where a is evaluated before b. For a simple assignment, GLSL
1529 // says to evaluate the left before the right. So, always, left
1530 // node then right node.
1531 {
1532 // get the left l-value, save it away
1533 builder.clearAccessChain();
1534 node->getLeft()->traverse(this);
1535 spv::Builder::AccessChain lValue = builder.getAccessChain();
1536
1537 // evaluate the right
1538 builder.clearAccessChain();
1539 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001540 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001541
1542 if (node->getOp() != glslang::EOpAssign) {
1543 // the left is also an r-value
1544 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001545 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001546
1547 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001548 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001549 TranslateNoContractionDecoration(node->getType().getQualifier()),
1550 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001551 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001552 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1553 node->getType().getBasicType());
1554
1555 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001556 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001557 }
1558
1559 // store the result
1560 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001561 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001562
1563 // assignments are expressions having an rValue after they are evaluated...
1564 builder.clearAccessChain();
1565 builder.setAccessChainRValue(rValue);
1566 }
1567 return false;
1568 case glslang::EOpIndexDirect:
1569 case glslang::EOpIndexDirectStruct:
1570 {
1571 // Get the left part of the access chain.
1572 node->getLeft()->traverse(this);
1573
1574 // Add the next element in the chain
1575
David Netoa901ffe2016-06-08 14:11:40 +01001576 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001577 if (! node->getLeft()->getType().isArray() &&
1578 node->getLeft()->getType().isVector() &&
1579 node->getOp() == glslang::EOpIndexDirect) {
1580 // This is essentially a hard-coded vector swizzle of size 1,
1581 // so short circuit the access-chain stuff with a swizzle.
1582 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001583 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001584 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001585 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001586 int spvIndex = glslangIndex;
1587 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1588 node->getOp() == glslang::EOpIndexDirectStruct)
1589 {
1590 // This may be, e.g., an anonymous block-member selection, which generally need
1591 // index remapping due to hidden members in anonymous blocks.
1592 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1593 assert(remapper.size() > 0);
1594 spvIndex = remapper[glslangIndex];
1595 }
John Kessenichebb50532016-05-16 19:22:05 -06001596
David Netoa901ffe2016-06-08 14:11:40 +01001597 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001598 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001599
1600 // Add capabilities here for accessing PointSize and clip/cull distance.
1601 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001602 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001603 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001604 }
1605 }
1606 return false;
1607 case glslang::EOpIndexIndirect:
1608 {
1609 // Structure or array or vector indirection.
1610 // Will use native SPIR-V access-chain for struct and array indirection;
1611 // matrices are arrays of vectors, so will also work for a matrix.
1612 // Will use the access chain's 'component' for variable index into a vector.
1613
1614 // This adapter is building access chains left to right.
1615 // Set up the access chain to the left.
1616 node->getLeft()->traverse(this);
1617
1618 // save it so that computing the right side doesn't trash it
1619 spv::Builder::AccessChain partial = builder.getAccessChain();
1620
1621 // compute the next index in the chain
1622 builder.clearAccessChain();
1623 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001624 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001625
John Kessenich5611c6d2018-04-05 11:25:02 -06001626 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1627
John Kessenich140f3df2015-06-26 16:58:36 -06001628 // restore the saved access chain
1629 builder.setAccessChain(partial);
1630
1631 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001632 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001633 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001634 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001635 }
1636 return false;
1637 case glslang::EOpVectorSwizzle:
1638 {
1639 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001640 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001641 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001642 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001643 }
1644 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001645 case glslang::EOpMatrixSwizzle:
1646 logger->missingFunctionality("matrix swizzle");
1647 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001648 case glslang::EOpLogicalOr:
1649 case glslang::EOpLogicalAnd:
1650 {
1651
1652 // These may require short circuiting, but can sometimes be done as straight
1653 // binary operations. The right operand must be short circuited if it has
1654 // side effects, and should probably be if it is complex.
1655 if (isTrivial(node->getRight()->getAsTyped()))
1656 break; // handle below as a normal binary operation
1657 // otherwise, we need to do dynamic short circuiting on the right operand
1658 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1659 builder.clearAccessChain();
1660 builder.setAccessChainRValue(result);
1661 }
1662 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001663 default:
1664 break;
1665 }
1666
1667 // Assume generic binary op...
1668
John Kessenich32cfd492016-02-02 12:37:46 -07001669 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001670 builder.clearAccessChain();
1671 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001672 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001673
John Kessenich32cfd492016-02-02 12:37:46 -07001674 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001675 builder.clearAccessChain();
1676 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001677 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001678
John Kessenich32cfd492016-02-02 12:37:46 -07001679 // get result
John Kessenichead86222018-03-28 18:01:20 -06001680 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001681 TranslateNoContractionDecoration(node->getType().getQualifier()),
1682 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001683 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001684 convertGlslangToSpvType(node->getType()), left, right,
1685 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
John Kessenich50e57562015-12-21 21:21:11 -07001687 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001688 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001689 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001690 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001691 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001692 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001693 return false;
1694 }
John Kessenich140f3df2015-06-26 16:58:36 -06001695}
1696
1697bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1698{
John Kesseniche485c7a2017-05-31 18:50:53 -06001699 builder.setLine(node->getLoc().line);
1700
qining40887662016-04-03 22:20:42 -04001701 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1702 if (node->getType().getQualifier().isSpecConstant())
1703 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1704
John Kessenichfc51d282015-08-19 13:34:18 -06001705 spv::Id result = spv::NoResult;
1706
1707 // try texturing first
1708 result = createImageTextureFunctionCall(node);
1709 if (result != spv::NoResult) {
1710 builder.clearAccessChain();
1711 builder.setAccessChainRValue(result);
1712
1713 return false; // done with this node
1714 }
1715
1716 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001717
1718 if (node->getOp() == glslang::EOpArrayLength) {
1719 // Quite special; won't want to evaluate the operand.
1720
John Kessenich5611c6d2018-04-05 11:25:02 -06001721 // Currently, the front-end does not allow .length() on an array until it is sized,
1722 // except for the last block membeor of an SSBO.
1723 // TODO: If this changes, link-time sized arrays might show up here, and need their
1724 // size extracted.
1725
John Kessenichc9a80832015-09-12 12:17:44 -06001726 // Normal .length() would have been constant folded by the front-end.
1727 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001728 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001729
John Kessenichc9a80832015-09-12 12:17:44 -06001730 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1731 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001732 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1733 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001734
1735 builder.clearAccessChain();
1736 builder.setAccessChainRValue(length);
1737
1738 return false;
1739 }
1740
John Kessenichfc51d282015-08-19 13:34:18 -06001741 // Start by evaluating the operand
1742
John Kessenich8c8505c2016-07-26 12:50:38 -06001743 // Does it need a swizzle inversion? If so, evaluation is inverted;
1744 // operate first on the swizzle base, then apply the swizzle.
1745 spv::Id invertedType = spv::NoType;
1746 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1747 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1748 invertedType = getInvertedSwizzleType(*node->getOperand());
1749
John Kessenich140f3df2015-06-26 16:58:36 -06001750 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001751 if (invertedType != spv::NoType)
1752 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1753 else
1754 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001755
Rex Xufc618912015-09-09 16:42:49 +08001756 spv::Id operand = spv::NoResult;
1757
1758 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1759 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001760 node->getOp() == glslang::EOpAtomicCounter ||
1761 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001762 operand = builder.accessChainGetLValue(); // Special case l-value operands
1763 else
John Kessenich32cfd492016-02-02 12:37:46 -07001764 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001765
John Kessenichead86222018-03-28 18:01:20 -06001766 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001767 TranslateNoContractionDecoration(node->getType().getQualifier()),
1768 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001769
1770 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001771 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001772 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001773
1774 // if not, then possibly an operation
1775 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001776 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001777
1778 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001779 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001780 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001781 builder.addDecoration(result, decorations.nonUniform);
1782 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001783
John Kessenich140f3df2015-06-26 16:58:36 -06001784 builder.clearAccessChain();
1785 builder.setAccessChainRValue(result);
1786
1787 return false; // done with this node
1788 }
1789
1790 // it must be a special case, check...
1791 switch (node->getOp()) {
1792 case glslang::EOpPostIncrement:
1793 case glslang::EOpPostDecrement:
1794 case glslang::EOpPreIncrement:
1795 case glslang::EOpPreDecrement:
1796 {
1797 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001798 spv::Id one = 0;
1799 if (node->getBasicType() == glslang::EbtFloat)
1800 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001801 else if (node->getBasicType() == glslang::EbtDouble)
1802 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001803 else if (node->getBasicType() == glslang::EbtFloat16)
1804 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001805 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1806 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001807 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1808 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001809 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1810 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001811 else
1812 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001813 glslang::TOperator op;
1814 if (node->getOp() == glslang::EOpPreIncrement ||
1815 node->getOp() == glslang::EOpPostIncrement)
1816 op = glslang::EOpAdd;
1817 else
1818 op = glslang::EOpSub;
1819
John Kessenichead86222018-03-28 18:01:20 -06001820 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001821 convertGlslangToSpvType(node->getType()), operand, one,
1822 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001823 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001824
1825 // The result of operation is always stored, but conditionally the
1826 // consumed result. The consumed result is always an r-value.
1827 builder.accessChainStore(result);
1828 builder.clearAccessChain();
1829 if (node->getOp() == glslang::EOpPreIncrement ||
1830 node->getOp() == glslang::EOpPreDecrement)
1831 builder.setAccessChainRValue(result);
1832 else
1833 builder.setAccessChainRValue(operand);
1834 }
1835
1836 return false;
1837
1838 case glslang::EOpEmitStreamVertex:
1839 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1840 return false;
1841 case glslang::EOpEndStreamPrimitive:
1842 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1843 return false;
1844
1845 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001846 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001847 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001848 }
John Kessenich140f3df2015-06-26 16:58:36 -06001849}
1850
1851bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1852{
qining27e04a02016-04-14 16:40:20 -04001853 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1854 if (node->getType().getQualifier().isSpecConstant())
1855 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1856
John Kessenichfc51d282015-08-19 13:34:18 -06001857 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001858 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1859 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001860
1861 // try texturing
1862 result = createImageTextureFunctionCall(node);
1863 if (result != spv::NoResult) {
1864 builder.clearAccessChain();
1865 builder.setAccessChainRValue(result);
1866
1867 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001868 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001869#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001870 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001871#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001872 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001873 // "imageStore" is a special case, which has no result
1874 return false;
1875 }
John Kessenichfc51d282015-08-19 13:34:18 -06001876
John Kessenich140f3df2015-06-26 16:58:36 -06001877 glslang::TOperator binOp = glslang::EOpNull;
1878 bool reduceComparison = true;
1879 bool isMatrix = false;
1880 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001881 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001882
1883 assert(node->getOp());
1884
John Kessenichf6640762016-08-01 19:44:00 -06001885 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001886
1887 switch (node->getOp()) {
1888 case glslang::EOpSequence:
1889 {
1890 if (preVisit)
1891 ++sequenceDepth;
1892 else
1893 --sequenceDepth;
1894
1895 if (sequenceDepth == 1) {
1896 // If this is the parent node of all the functions, we want to see them
1897 // early, so all call points have actual SPIR-V functions to reference.
1898 // In all cases, still let the traverser visit the children for us.
1899 makeFunctions(node->getAsAggregate()->getSequence());
1900
John Kessenich6fccb3c2016-09-19 16:01:41 -06001901 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001902 // anything else gets there, so visit out of order, doing them all now.
1903 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1904
John Kessenich6a60c2f2016-12-08 21:01:59 -07001905 // 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 -06001906 // so do them manually.
1907 visitFunctions(node->getAsAggregate()->getSequence());
1908
1909 return false;
1910 }
1911
1912 return true;
1913 }
1914 case glslang::EOpLinkerObjects:
1915 {
1916 if (visit == glslang::EvPreVisit)
1917 linkageOnly = true;
1918 else
1919 linkageOnly = false;
1920
1921 return true;
1922 }
1923 case glslang::EOpComma:
1924 {
1925 // processing from left to right naturally leaves the right-most
1926 // lying around in the access chain
1927 glslang::TIntermSequence& glslangOperands = node->getSequence();
1928 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1929 glslangOperands[i]->traverse(this);
1930
1931 return false;
1932 }
1933 case glslang::EOpFunction:
1934 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001935 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001936 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001937 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001938 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001939 } else {
1940 handleFunctionEntry(node);
1941 }
1942 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001943 if (inEntryPoint)
1944 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001945 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001946 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001947 }
1948
1949 return true;
1950 case glslang::EOpParameters:
1951 // Parameters will have been consumed by EOpFunction processing, but not
1952 // the body, so we still visited the function node's children, making this
1953 // child redundant.
1954 return false;
1955 case glslang::EOpFunctionCall:
1956 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001957 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001958 if (node->isUserDefined())
1959 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001960 // 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 -07001961 if (result) {
1962 builder.clearAccessChain();
1963 builder.setAccessChainRValue(result);
1964 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001965 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001966
1967 return false;
1968 }
1969 case glslang::EOpConstructMat2x2:
1970 case glslang::EOpConstructMat2x3:
1971 case glslang::EOpConstructMat2x4:
1972 case glslang::EOpConstructMat3x2:
1973 case glslang::EOpConstructMat3x3:
1974 case glslang::EOpConstructMat3x4:
1975 case glslang::EOpConstructMat4x2:
1976 case glslang::EOpConstructMat4x3:
1977 case glslang::EOpConstructMat4x4:
1978 case glslang::EOpConstructDMat2x2:
1979 case glslang::EOpConstructDMat2x3:
1980 case glslang::EOpConstructDMat2x4:
1981 case glslang::EOpConstructDMat3x2:
1982 case glslang::EOpConstructDMat3x3:
1983 case glslang::EOpConstructDMat3x4:
1984 case glslang::EOpConstructDMat4x2:
1985 case glslang::EOpConstructDMat4x3:
1986 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001987 case glslang::EOpConstructIMat2x2:
1988 case glslang::EOpConstructIMat2x3:
1989 case glslang::EOpConstructIMat2x4:
1990 case glslang::EOpConstructIMat3x2:
1991 case glslang::EOpConstructIMat3x3:
1992 case glslang::EOpConstructIMat3x4:
1993 case glslang::EOpConstructIMat4x2:
1994 case glslang::EOpConstructIMat4x3:
1995 case glslang::EOpConstructIMat4x4:
1996 case glslang::EOpConstructUMat2x2:
1997 case glslang::EOpConstructUMat2x3:
1998 case glslang::EOpConstructUMat2x4:
1999 case glslang::EOpConstructUMat3x2:
2000 case glslang::EOpConstructUMat3x3:
2001 case glslang::EOpConstructUMat3x4:
2002 case glslang::EOpConstructUMat4x2:
2003 case glslang::EOpConstructUMat4x3:
2004 case glslang::EOpConstructUMat4x4:
2005 case glslang::EOpConstructBMat2x2:
2006 case glslang::EOpConstructBMat2x3:
2007 case glslang::EOpConstructBMat2x4:
2008 case glslang::EOpConstructBMat3x2:
2009 case glslang::EOpConstructBMat3x3:
2010 case glslang::EOpConstructBMat3x4:
2011 case glslang::EOpConstructBMat4x2:
2012 case glslang::EOpConstructBMat4x3:
2013 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002014 case glslang::EOpConstructF16Mat2x2:
2015 case glslang::EOpConstructF16Mat2x3:
2016 case glslang::EOpConstructF16Mat2x4:
2017 case glslang::EOpConstructF16Mat3x2:
2018 case glslang::EOpConstructF16Mat3x3:
2019 case glslang::EOpConstructF16Mat3x4:
2020 case glslang::EOpConstructF16Mat4x2:
2021 case glslang::EOpConstructF16Mat4x3:
2022 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002023 isMatrix = true;
2024 // fall through
2025 case glslang::EOpConstructFloat:
2026 case glslang::EOpConstructVec2:
2027 case glslang::EOpConstructVec3:
2028 case glslang::EOpConstructVec4:
2029 case glslang::EOpConstructDouble:
2030 case glslang::EOpConstructDVec2:
2031 case glslang::EOpConstructDVec3:
2032 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002033 case glslang::EOpConstructFloat16:
2034 case glslang::EOpConstructF16Vec2:
2035 case glslang::EOpConstructF16Vec3:
2036 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002037 case glslang::EOpConstructBool:
2038 case glslang::EOpConstructBVec2:
2039 case glslang::EOpConstructBVec3:
2040 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002041 case glslang::EOpConstructInt8:
2042 case glslang::EOpConstructI8Vec2:
2043 case glslang::EOpConstructI8Vec3:
2044 case glslang::EOpConstructI8Vec4:
2045 case glslang::EOpConstructUint8:
2046 case glslang::EOpConstructU8Vec2:
2047 case glslang::EOpConstructU8Vec3:
2048 case glslang::EOpConstructU8Vec4:
2049 case glslang::EOpConstructInt16:
2050 case glslang::EOpConstructI16Vec2:
2051 case glslang::EOpConstructI16Vec3:
2052 case glslang::EOpConstructI16Vec4:
2053 case glslang::EOpConstructUint16:
2054 case glslang::EOpConstructU16Vec2:
2055 case glslang::EOpConstructU16Vec3:
2056 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002057 case glslang::EOpConstructInt:
2058 case glslang::EOpConstructIVec2:
2059 case glslang::EOpConstructIVec3:
2060 case glslang::EOpConstructIVec4:
2061 case glslang::EOpConstructUint:
2062 case glslang::EOpConstructUVec2:
2063 case glslang::EOpConstructUVec3:
2064 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002065 case glslang::EOpConstructInt64:
2066 case glslang::EOpConstructI64Vec2:
2067 case glslang::EOpConstructI64Vec3:
2068 case glslang::EOpConstructI64Vec4:
2069 case glslang::EOpConstructUint64:
2070 case glslang::EOpConstructU64Vec2:
2071 case glslang::EOpConstructU64Vec3:
2072 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002073 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002074 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002075 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002076 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002077 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002078 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002080 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002081 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002082 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002083 std::vector<spv::Id> constituents;
2084 for (int c = 0; c < (int)arguments.size(); ++c)
2085 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002086 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002087 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002088 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002089 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002090 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002091
2092 builder.clearAccessChain();
2093 builder.setAccessChainRValue(constructed);
2094
2095 return false;
2096 }
2097
2098 // These six are component-wise compares with component-wise results.
2099 // Forward on to createBinaryOperation(), requesting a vector result.
2100 case glslang::EOpLessThan:
2101 case glslang::EOpGreaterThan:
2102 case glslang::EOpLessThanEqual:
2103 case glslang::EOpGreaterThanEqual:
2104 case glslang::EOpVectorEqual:
2105 case glslang::EOpVectorNotEqual:
2106 {
2107 // Map the operation to a binary
2108 binOp = node->getOp();
2109 reduceComparison = false;
2110 switch (node->getOp()) {
2111 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2112 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2113 default: binOp = node->getOp(); break;
2114 }
2115
2116 break;
2117 }
2118 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002119 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002120 binOp = glslang::EOpMul;
2121 break;
2122 case glslang::EOpOuterProduct:
2123 // two vectors multiplied to make a matrix
2124 binOp = glslang::EOpOuterProduct;
2125 break;
2126 case glslang::EOpDot:
2127 {
qining25262b32016-05-06 17:25:16 -04002128 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002129 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002130 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002131 binOp = glslang::EOpMul;
2132 break;
2133 }
2134 case glslang::EOpMod:
2135 // when an aggregate, this is the floating-point mod built-in function,
2136 // which can be emitted by the one in createBinaryOperation()
2137 binOp = glslang::EOpMod;
2138 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002139 case glslang::EOpEmitVertex:
2140 case glslang::EOpEndPrimitive:
2141 case glslang::EOpBarrier:
2142 case glslang::EOpMemoryBarrier:
2143 case glslang::EOpMemoryBarrierAtomicCounter:
2144 case glslang::EOpMemoryBarrierBuffer:
2145 case glslang::EOpMemoryBarrierImage:
2146 case glslang::EOpMemoryBarrierShared:
2147 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002148 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002149 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002150 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002151 case glslang::EOpWorkgroupMemoryBarrier:
2152 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002153 case glslang::EOpSubgroupBarrier:
2154 case glslang::EOpSubgroupMemoryBarrier:
2155 case glslang::EOpSubgroupMemoryBarrierBuffer:
2156 case glslang::EOpSubgroupMemoryBarrierImage:
2157 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002158 noReturnValue = true;
2159 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2160 break;
2161
Jeff Bolz36831c92018-09-05 10:11:41 -05002162 case glslang::EOpAtomicStore:
2163 noReturnValue = true;
2164 // fallthrough
2165 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002166 case glslang::EOpAtomicAdd:
2167 case glslang::EOpAtomicMin:
2168 case glslang::EOpAtomicMax:
2169 case glslang::EOpAtomicAnd:
2170 case glslang::EOpAtomicOr:
2171 case glslang::EOpAtomicXor:
2172 case glslang::EOpAtomicExchange:
2173 case glslang::EOpAtomicCompSwap:
2174 atomic = true;
2175 break;
2176
John Kessenich0d0c6d32017-07-23 16:08:26 -06002177 case glslang::EOpAtomicCounterAdd:
2178 case glslang::EOpAtomicCounterSubtract:
2179 case glslang::EOpAtomicCounterMin:
2180 case glslang::EOpAtomicCounterMax:
2181 case glslang::EOpAtomicCounterAnd:
2182 case glslang::EOpAtomicCounterOr:
2183 case glslang::EOpAtomicCounterXor:
2184 case glslang::EOpAtomicCounterExchange:
2185 case glslang::EOpAtomicCounterCompSwap:
2186 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2187 builder.addCapability(spv::CapabilityAtomicStorageOps);
2188 atomic = true;
2189 break;
2190
Chao Chen3c366992018-09-19 11:41:59 -07002191#ifdef NV_EXTENSIONS
2192 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2193 noReturnValue = true;
2194 break;
2195#endif
2196
John Kessenich140f3df2015-06-26 16:58:36 -06002197 default:
2198 break;
2199 }
2200
2201 //
2202 // See if it maps to a regular operation.
2203 //
John Kessenich140f3df2015-06-26 16:58:36 -06002204 if (binOp != glslang::EOpNull) {
2205 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2206 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2207 assert(left && right);
2208
2209 builder.clearAccessChain();
2210 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002211 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002212
2213 builder.clearAccessChain();
2214 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002215 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002216
John Kesseniche485c7a2017-05-31 18:50:53 -06002217 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002218 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002219 TranslateNoContractionDecoration(node->getType().getQualifier()),
2220 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002221 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002222 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002223 left->getType().getBasicType(), reduceComparison);
2224
2225 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002226 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002227 builder.clearAccessChain();
2228 builder.setAccessChainRValue(result);
2229
2230 return false;
2231 }
2232
John Kessenich426394d2015-07-23 10:22:48 -06002233 //
2234 // Create the list of operands.
2235 //
John Kessenich140f3df2015-06-26 16:58:36 -06002236 glslang::TIntermSequence& glslangOperands = node->getSequence();
2237 std::vector<spv::Id> operands;
2238 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002239 // special case l-value operands; there are just a few
2240 bool lvalue = false;
2241 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002242 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002243 case glslang::EOpModf:
2244 if (arg == 1)
2245 lvalue = true;
2246 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002247 case glslang::EOpInterpolateAtSample:
2248 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002249#ifdef AMD_EXTENSIONS
2250 case glslang::EOpInterpolateAtVertex:
2251#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002252 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002253 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002254
2255 // Does it need a swizzle inversion? If so, evaluation is inverted;
2256 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002257 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002258 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2259 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2260 }
Rex Xu7a26c172015-12-08 17:12:09 +08002261 break;
Rex Xud4782c12015-09-06 16:30:11 +08002262 case glslang::EOpAtomicAdd:
2263 case glslang::EOpAtomicMin:
2264 case glslang::EOpAtomicMax:
2265 case glslang::EOpAtomicAnd:
2266 case glslang::EOpAtomicOr:
2267 case glslang::EOpAtomicXor:
2268 case glslang::EOpAtomicExchange:
2269 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002270 case glslang::EOpAtomicLoad:
2271 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002272 case glslang::EOpAtomicCounterAdd:
2273 case glslang::EOpAtomicCounterSubtract:
2274 case glslang::EOpAtomicCounterMin:
2275 case glslang::EOpAtomicCounterMax:
2276 case glslang::EOpAtomicCounterAnd:
2277 case glslang::EOpAtomicCounterOr:
2278 case glslang::EOpAtomicCounterXor:
2279 case glslang::EOpAtomicCounterExchange:
2280 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002281 if (arg == 0)
2282 lvalue = true;
2283 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002284 case glslang::EOpAddCarry:
2285 case glslang::EOpSubBorrow:
2286 if (arg == 2)
2287 lvalue = true;
2288 break;
2289 case glslang::EOpUMulExtended:
2290 case glslang::EOpIMulExtended:
2291 if (arg >= 2)
2292 lvalue = true;
2293 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002294 default:
2295 break;
2296 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002297 builder.clearAccessChain();
2298 if (invertedType != spv::NoType && arg == 0)
2299 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2300 else
2301 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002302 if (lvalue)
2303 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002304 else {
2305 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002306 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002307 }
John Kessenich140f3df2015-06-26 16:58:36 -06002308 }
John Kessenich426394d2015-07-23 10:22:48 -06002309
John Kesseniche485c7a2017-05-31 18:50:53 -06002310 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002311 if (atomic) {
2312 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002313 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002314 } else {
2315 // Pass through to generic operations.
2316 switch (glslangOperands.size()) {
2317 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002318 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002319 break;
2320 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002321 {
2322 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002323 TranslateNoContractionDecoration(node->getType().getQualifier()),
2324 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002325 result = createUnaryOperation(
2326 node->getOp(), decorations,
2327 resultType(), operands.front(),
2328 glslangOperands[0]->getAsTyped()->getBasicType());
2329 }
John Kessenich426394d2015-07-23 10:22:48 -06002330 break;
2331 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002332 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002333 break;
2334 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002335 if (invertedType)
2336 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002337 }
2338
2339 if (noReturnValue)
2340 return false;
2341
2342 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002343 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002344 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002345 } else {
2346 builder.clearAccessChain();
2347 builder.setAccessChainRValue(result);
2348 return false;
2349 }
2350}
2351
John Kessenich433e9ff2017-01-26 20:31:11 -07002352// This path handles both if-then-else and ?:
2353// The if-then-else has a node type of void, while
2354// ?: has either a void or a non-void node type
2355//
2356// Leaving the result, when not void:
2357// GLSL only has r-values as the result of a :?, but
2358// if we have an l-value, that can be more efficient if it will
2359// become the base of a complex r-value expression, because the
2360// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002361bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2362{
John Kessenich4bee5312018-02-20 21:29:05 -07002363 // See if it simple and safe, or required, to execute both sides.
2364 // Crucially, side effects must be either semantically required or avoided,
2365 // and there are performance trade-offs.
2366 // Return true if required or a good idea (and safe) to execute both sides,
2367 // false otherwise.
2368 const auto bothSidesPolicy = [&]() -> bool {
2369 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002370 if (node->getTrueBlock() == nullptr ||
2371 node->getFalseBlock() == nullptr)
2372 return false;
2373
John Kessenich4bee5312018-02-20 21:29:05 -07002374 // required? (unless we write additional code to look for side effects
2375 // and make performance trade-offs if none are present)
2376 if (!node->getShortCircuit())
2377 return true;
2378
2379 // if not required to execute both, decide based on performance/practicality...
2380
2381 // see if OpSelect can handle it
2382 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2383 node->getBasicType() == glslang::EbtVoid)
2384 return false;
2385
John Kessenich433e9ff2017-01-26 20:31:11 -07002386 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2387 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2388
2389 // return true if a single operand to ? : is okay for OpSelect
2390 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002391 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002392 };
2393
2394 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2395 operandOkay(node->getFalseBlock()->getAsTyped());
2396 };
2397
John Kessenich4bee5312018-02-20 21:29:05 -07002398 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2399 // emit the condition before doing anything with selection
2400 node->getCondition()->traverse(this);
2401 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2402
2403 // Find a way of executing both sides and selecting the right result.
2404 const auto executeBothSides = [&]() -> void {
2405 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002406 node->getTrueBlock()->traverse(this);
2407 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2408 node->getFalseBlock()->traverse(this);
2409 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2410
John Kesseniche485c7a2017-05-31 18:50:53 -06002411 builder.setLine(node->getLoc().line);
2412
John Kessenich4bee5312018-02-20 21:29:05 -07002413 // done if void
2414 if (node->getBasicType() == glslang::EbtVoid)
2415 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002416
John Kessenich4bee5312018-02-20 21:29:05 -07002417 // emit code to select between trueValue and falseValue
2418
2419 // see if OpSelect can handle it
2420 if (node->getType().isScalar() || node->getType().isVector()) {
2421 // Emit OpSelect for this selection.
2422
2423 // smear condition to vector, if necessary (AST is always scalar)
2424 if (builder.isVector(trueValue))
2425 condition = builder.smearScalar(spv::NoPrecision, condition,
2426 builder.makeVectorType(builder.makeBoolType(),
2427 builder.getNumComponents(trueValue)));
2428
2429 // OpSelect
2430 result = builder.createTriOp(spv::OpSelect,
2431 convertGlslangToSpvType(node->getType()), condition,
2432 trueValue, falseValue);
2433
2434 builder.clearAccessChain();
2435 builder.setAccessChainRValue(result);
2436 } else {
2437 // We need control flow to select the result.
2438 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2439 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2440
2441 // Selection control:
2442 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2443
2444 // make an "if" based on the value created by the condition
2445 spv::Builder::If ifBuilder(condition, control, builder);
2446
2447 // emit the "then" statement
2448 builder.createStore(trueValue, result);
2449 ifBuilder.makeBeginElse();
2450 // emit the "else" statement
2451 builder.createStore(falseValue, result);
2452
2453 // finish off the control flow
2454 ifBuilder.makeEndIf();
2455
2456 builder.clearAccessChain();
2457 builder.setAccessChainLValue(result);
2458 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002459 };
2460
John Kessenich4bee5312018-02-20 21:29:05 -07002461 // Execute the one side needed, as per the condition
2462 const auto executeOneSide = [&]() {
2463 // Always emit control flow.
2464 if (node->getBasicType() != glslang::EbtVoid)
2465 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002466
John Kessenich4bee5312018-02-20 21:29:05 -07002467 // Selection control:
2468 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2469
2470 // make an "if" based on the value created by the condition
2471 spv::Builder::If ifBuilder(condition, control, builder);
2472
2473 // emit the "then" statement
2474 if (node->getTrueBlock() != nullptr) {
2475 node->getTrueBlock()->traverse(this);
2476 if (result != spv::NoResult)
2477 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2478 }
2479
2480 if (node->getFalseBlock() != nullptr) {
2481 ifBuilder.makeBeginElse();
2482 // emit the "else" statement
2483 node->getFalseBlock()->traverse(this);
2484 if (result != spv::NoResult)
2485 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2486 }
2487
2488 // finish off the control flow
2489 ifBuilder.makeEndIf();
2490
2491 if (result != spv::NoResult) {
2492 builder.clearAccessChain();
2493 builder.setAccessChainLValue(result);
2494 }
2495 };
2496
2497 // Try for OpSelect (or a requirement to execute both sides)
2498 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002499 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2500 if (node->getType().getQualifier().isSpecConstant())
2501 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002502 executeBothSides();
2503 } else
2504 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002505
2506 return false;
2507}
2508
2509bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2510{
2511 // emit and get the condition before doing anything with switch
2512 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002513 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002514
Rex Xu57e65922017-07-04 23:23:40 +08002515 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002516 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002517
John Kessenich140f3df2015-06-26 16:58:36 -06002518 // browse the children to sort out code segments
2519 int defaultSegment = -1;
2520 std::vector<TIntermNode*> codeSegments;
2521 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2522 std::vector<int> caseValues;
2523 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2524 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2525 TIntermNode* child = *c;
2526 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002527 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002528 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002529 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002530 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2531 } else
2532 codeSegments.push_back(child);
2533 }
2534
qining25262b32016-05-06 17:25:16 -04002535 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002536 // statements between the last case and the end of the switch statement
2537 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2538 (int)codeSegments.size() == defaultSegment)
2539 codeSegments.push_back(nullptr);
2540
2541 // make the switch statement
2542 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002543 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002544
2545 // emit all the code in the segments
2546 breakForLoop.push(false);
2547 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2548 builder.nextSwitchSegment(segmentBlocks, s);
2549 if (codeSegments[s])
2550 codeSegments[s]->traverse(this);
2551 else
2552 builder.addSwitchBreak();
2553 }
2554 breakForLoop.pop();
2555
2556 builder.endSwitch(segmentBlocks);
2557
2558 return false;
2559}
2560
2561void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2562{
2563 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002564 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002565
2566 builder.clearAccessChain();
2567 builder.setAccessChainRValue(constant);
2568}
2569
2570bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2571{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002572 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002573 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002574
2575 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002576 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2577 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002578
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002579 // Spec requires back edges to target header blocks, and every header block
2580 // must dominate its merge block. Make a header block first to ensure these
2581 // conditions are met. By definition, it will contain OpLoopMerge, followed
2582 // by a block-ending branch. But we don't want to put any other body/test
2583 // instructions in it, since the body/test may have arbitrary instructions,
2584 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002585 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002586 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002587 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002588 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002589 spv::Block& test = builder.makeNewBlock();
2590 builder.createBranch(&test);
2591
2592 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002593 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002594 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002595 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2596
2597 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002598 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002599 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002600 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002601 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002602 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002603
2604 builder.setBuildPoint(&blocks.continue_target);
2605 if (node->getTerminal())
2606 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002607 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002608 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002609 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002610 builder.createBranch(&blocks.body);
2611
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002612 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002613 builder.setBuildPoint(&blocks.body);
2614 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002615 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002616 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002617 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002618
2619 builder.setBuildPoint(&blocks.continue_target);
2620 if (node->getTerminal())
2621 node->getTerminal()->traverse(this);
2622 if (node->getTest()) {
2623 node->getTest()->traverse(this);
2624 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002625 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002626 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002627 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002628 // TODO: unless there was a break/return/discard instruction
2629 // somewhere in the body, this is an infinite loop, so we should
2630 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002631 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002632 }
John Kessenich140f3df2015-06-26 16:58:36 -06002633 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002634 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002635 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002636 return false;
2637}
2638
2639bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2640{
2641 if (node->getExpression())
2642 node->getExpression()->traverse(this);
2643
John Kesseniche485c7a2017-05-31 18:50:53 -06002644 builder.setLine(node->getLoc().line);
2645
John Kessenich140f3df2015-06-26 16:58:36 -06002646 switch (node->getFlowOp()) {
2647 case glslang::EOpKill:
2648 builder.makeDiscard();
2649 break;
2650 case glslang::EOpBreak:
2651 if (breakForLoop.top())
2652 builder.createLoopExit();
2653 else
2654 builder.addSwitchBreak();
2655 break;
2656 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002657 builder.createLoopContinue();
2658 break;
2659 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002660 if (node->getExpression()) {
2661 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2662 spv::Id returnId = accessChainLoad(glslangReturnType);
2663 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2664 builder.clearAccessChain();
2665 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2666 builder.setAccessChainLValue(copyId);
2667 multiTypeStore(glslangReturnType, returnId);
2668 returnId = builder.createLoad(copyId);
2669 }
2670 builder.makeReturn(false, returnId);
2671 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002672 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002673
2674 builder.clearAccessChain();
2675 break;
2676
2677 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002678 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002679 break;
2680 }
2681
2682 return false;
2683}
2684
2685spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2686{
qining25262b32016-05-06 17:25:16 -04002687 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002688 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002689 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002690 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002691 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002692 }
2693
2694 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002695 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002696 spv::Id spvType = convertGlslangToSpvType(node->getType());
2697
Rex Xucabbb782017-03-24 13:41:14 +08002698 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2699 node->getType().containsBasicType(glslang::EbtInt16) ||
2700 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002701 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002702 switch (storageClass) {
2703 case spv::StorageClassInput:
2704 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002705 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002706 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002707 break;
2708 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002709 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002710 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002711 break;
2712 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002713 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002714 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2715 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002716 else
2717 builder.addCapability(spv::CapabilityStorageUniform16);
2718 break;
2719 case spv::StorageClassStorageBuffer:
2720 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2721 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2722 break;
2723 default:
2724 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002725 }
2726 }
Rex Xuf89ad982017-04-07 23:22:33 +08002727
John Kessenich312dcfb2018-07-03 13:19:51 -06002728 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2729 node->getType().containsBasicType(glslang::EbtUint8);
2730 if (contains8BitType) {
2731 if (storageClass == spv::StorageClassPushConstant) {
2732 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2733 builder.addCapability(spv::CapabilityStoragePushConstant8);
2734 } else if (storageClass == spv::StorageClassUniform) {
2735 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2736 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2737 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2738 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2739 }
2740 }
2741
John Kessenich140f3df2015-06-26 16:58:36 -06002742 const char* name = node->getName().c_str();
2743 if (glslang::IsAnonymous(name))
2744 name = "";
2745
2746 return builder.createVariable(storageClass, spvType, name);
2747}
2748
2749// Return type Id of the sampled type.
2750spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2751{
2752 switch (sampler.type) {
2753 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002754#ifdef AMD_EXTENSIONS
2755 case glslang::EbtFloat16:
2756 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2757 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2758 return builder.makeFloatType(16);
2759#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002760 case glslang::EbtInt: return builder.makeIntType(32);
2761 case glslang::EbtUint: return builder.makeUintType(32);
2762 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002763 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002764 return builder.makeFloatType(32);
2765 }
2766}
2767
John Kessenich8c8505c2016-07-26 12:50:38 -06002768// If node is a swizzle operation, return the type that should be used if
2769// the swizzle base is first consumed by another operation, before the swizzle
2770// is applied.
2771spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2772{
John Kessenichecba76f2017-01-06 00:34:48 -07002773 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002774 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2775 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2776 else
2777 return spv::NoType;
2778}
2779
2780// When inverting a swizzle with a parent op, this function
2781// will apply the swizzle operation to a completed parent operation.
2782spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2783{
2784 std::vector<unsigned> swizzle;
2785 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2786 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2787}
2788
John Kessenich8c8505c2016-07-26 12:50:38 -06002789// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2790void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2791{
2792 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2793 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2794 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2795}
2796
John Kessenich3ac051e2015-12-20 11:29:16 -07002797// Convert from a glslang type to an SPV type, by calling into a
2798// recursive version of this function. This establishes the inherited
2799// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002800spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2801{
John Kessenichead86222018-03-28 18:01:20 -06002802 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002803}
2804
2805// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002806// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002807// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002808spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2809 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002810{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002811 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002812
2813 switch (type.getBasicType()) {
2814 case glslang::EbtVoid:
2815 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002816 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002817 break;
2818 case glslang::EbtFloat:
2819 spvType = builder.makeFloatType(32);
2820 break;
2821 case glslang::EbtDouble:
2822 spvType = builder.makeFloatType(64);
2823 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002824 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002825 spvType = builder.makeFloatType(16);
2826 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002827 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002828 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2829 // a 32-bit int where non-0 means true.
2830 if (explicitLayout != glslang::ElpNone)
2831 spvType = builder.makeUintType(32);
2832 else
2833 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002834 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002835 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002836 spvType = builder.makeIntType(8);
2837 break;
2838 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002839 spvType = builder.makeUintType(8);
2840 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002841 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002842 spvType = builder.makeIntType(16);
2843 break;
2844 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002845 spvType = builder.makeUintType(16);
2846 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002847 case glslang::EbtInt:
2848 spvType = builder.makeIntType(32);
2849 break;
2850 case glslang::EbtUint:
2851 spvType = builder.makeUintType(32);
2852 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002853 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002854 spvType = builder.makeIntType(64);
2855 break;
2856 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002857 spvType = builder.makeUintType(64);
2858 break;
John Kessenich426394d2015-07-23 10:22:48 -06002859 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002860 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002861 spvType = builder.makeUintType(32);
2862 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002863 case glslang::EbtSampler:
2864 {
2865 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002866 if (sampler.sampler) {
2867 // pure sampler
2868 spvType = builder.makeSamplerType();
2869 } else {
2870 // an image is present, make its type
2871 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2872 sampler.image ? 2 : 1, TranslateImageFormat(type));
2873 if (sampler.combined) {
2874 // already has both image and sampler, make the combined type
2875 spvType = builder.makeSampledImageType(spvType);
2876 }
John Kessenich55e7d112015-11-15 21:33:39 -07002877 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002878 }
John Kessenich140f3df2015-06-26 16:58:36 -06002879 break;
2880 case glslang::EbtStruct:
2881 case glslang::EbtBlock:
2882 {
2883 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002884 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002885
2886 // Try to share structs for different layouts, but not yet for other
2887 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002888 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002889 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002890 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002891 break;
2892
2893 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002894 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002895 memberRemapper[glslangMembers].resize(glslangMembers->size());
2896 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002897 }
2898 break;
2899 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002900 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002901 break;
2902 }
2903
2904 if (type.isMatrix())
2905 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2906 else {
2907 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2908 if (type.getVectorSize() > 1)
2909 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2910 }
2911
2912 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002913 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2914
John Kessenichc9a80832015-09-12 12:17:44 -06002915 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002916 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002917 // We need to decorate array strides for types needing explicit layout, except blocks.
2918 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002919 // Use a dummy glslang type for querying internal strides of
2920 // arrays of arrays, but using just a one-dimensional array.
2921 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002922 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2923 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002924
2925 // Will compute the higher-order strides here, rather than making a whole
2926 // pile of types and doing repetitive recursion on their contents.
2927 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2928 }
John Kessenichf8842e52016-01-04 19:22:56 -07002929
2930 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002931 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002932 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002933 if (stride > 0)
2934 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002935 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002936 }
2937 } else {
2938 // single-dimensional array, and don't yet have stride
2939
John Kessenichf8842e52016-01-04 19:22:56 -07002940 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002941 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2942 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002943 }
John Kessenich31ed4832015-09-09 17:51:38 -06002944
John Kessenichead86222018-03-28 18:01:20 -06002945 // Do the outer dimension, which might not be known for a runtime-sized array.
2946 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2947 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002948 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002949 else {
2950 if (!lastBufferBlockMember) {
2951 builder.addExtension("SPV_EXT_descriptor_indexing");
2952 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2953 }
John Kessenichead86222018-03-28 18:01:20 -06002954 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002955 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002956 if (stride > 0)
2957 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002958 }
2959
2960 return spvType;
2961}
2962
John Kessenich0e737842017-03-24 18:38:16 -06002963// TODO: this functionality should exist at a higher level, in creating the AST
2964//
2965// Identify interface members that don't have their required extension turned on.
2966//
2967bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2968{
Chao Chen3c366992018-09-19 11:41:59 -07002969#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06002970 auto& extensions = glslangIntermediate->getRequestedExtensions();
2971
Rex Xubcf291a2017-03-29 23:01:36 +08002972 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2973 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2974 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002975 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2976 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2977 return true;
Chao Chen3c366992018-09-19 11:41:59 -07002978
2979 if (glslangIntermediate->getStage() != EShLangMeshNV) {
2980 if (member.getFieldName() == "gl_ViewportMask" &&
2981 extensions.find("GL_NV_viewport_array2") == extensions.end())
2982 return true;
2983 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2984 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2985 return true;
2986 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2987 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2988 return true;
2989 }
2990#endif
John Kessenich0e737842017-03-24 18:38:16 -06002991
2992 return false;
2993};
2994
John Kessenich6090df02016-06-30 21:18:02 -06002995// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2996// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2997// Mutually recursive with convertGlslangToSpvType().
2998spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2999 const glslang::TTypeList* glslangMembers,
3000 glslang::TLayoutPacking explicitLayout,
3001 const glslang::TQualifier& qualifier)
3002{
3003 // Create a vector of struct types for SPIR-V to consume
3004 std::vector<spv::Id> spvMembers;
3005 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06003006 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3007 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3008 if (glslangMember.hiddenMember()) {
3009 ++memberDelta;
3010 if (type.getBasicType() == glslang::EbtBlock)
3011 memberRemapper[glslangMembers][i] = -1;
3012 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003013 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003014 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003015 if (filterMember(glslangMember))
3016 continue;
3017 }
John Kessenich6090df02016-06-30 21:18:02 -06003018 // modify just this child's view of the qualifier
3019 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3020 InheritQualifiers(memberQualifier, qualifier);
3021
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003022 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003023 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003024 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003025
3026 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003027 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3028 i == (int)glslangMembers->size() - 1;
3029 spvMembers.push_back(
3030 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003031 }
3032 }
3033
3034 // Make the SPIR-V type
3035 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003036 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003037 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3038
3039 // Decorate it
3040 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3041
3042 return spvType;
3043}
3044
3045void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3046 const glslang::TTypeList* glslangMembers,
3047 glslang::TLayoutPacking explicitLayout,
3048 const glslang::TQualifier& qualifier,
3049 spv::Id spvType)
3050{
3051 // Name and decorate the non-hidden members
3052 int offset = -1;
3053 int locationOffset = 0; // for use within the members of this struct
3054 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3055 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3056 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003057 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003058 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003059 if (filterMember(glslangMember))
3060 continue;
3061 }
John Kessenich6090df02016-06-30 21:18:02 -06003062
3063 // modify just this child's view of the qualifier
3064 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3065 InheritQualifiers(memberQualifier, qualifier);
3066
3067 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003068 if (member < 0)
3069 continue;
3070
3071 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3072 builder.addMemberDecoration(spvType, member,
3073 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3074 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3075 // Add interpolation and auxiliary storage decorations only to
3076 // top-level members of Input and Output storage classes
3077 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3078 type.getQualifier().storage == glslang::EvqVaryingOut) {
3079 if (type.getBasicType() == glslang::EbtBlock ||
3080 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3081 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3082 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003083#ifdef NV_EXTENSIONS
3084 addMeshNVDecoration(spvType, member, memberQualifier);
3085#endif
John Kessenich6090df02016-06-30 21:18:02 -06003086 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003087 }
3088 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003089
John Kessenich5d610ee2018-03-07 18:05:55 -07003090 if (type.getBasicType() == glslang::EbtBlock &&
3091 qualifier.storage == glslang::EvqBuffer) {
3092 // Add memory decorations only to top-level members of shader storage block
3093 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003094 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003095 for (unsigned int i = 0; i < memory.size(); ++i)
3096 builder.addMemberDecoration(spvType, member, memory[i]);
3097 }
John Kessenich6090df02016-06-30 21:18:02 -06003098
John Kessenich5d610ee2018-03-07 18:05:55 -07003099 // Location assignment was already completed correctly by the front end,
3100 // just track whether a member needs to be decorated.
3101 // Ignore member locations if the container is an array, as that's
3102 // ill-specified and decisions have been made to not allow this.
3103 if (! type.isArray() && memberQualifier.hasLocation())
3104 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003105
John Kessenich5d610ee2018-03-07 18:05:55 -07003106 if (qualifier.hasLocation()) // track for upcoming inheritance
3107 locationOffset += glslangIntermediate->computeTypeLocationSize(
3108 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003109
John Kessenich5d610ee2018-03-07 18:05:55 -07003110 // component, XFB, others
3111 if (glslangMember.getQualifier().hasComponent())
3112 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3113 glslangMember.getQualifier().layoutComponent);
3114 if (glslangMember.getQualifier().hasXfbOffset())
3115 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3116 glslangMember.getQualifier().layoutXfbOffset);
3117 else if (explicitLayout != glslang::ElpNone) {
3118 // figure out what to do with offset, which is accumulating
3119 int nextOffset;
3120 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3121 if (offset >= 0)
3122 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3123 offset = nextOffset;
3124 }
John Kessenich6090df02016-06-30 21:18:02 -06003125
John Kessenich5d610ee2018-03-07 18:05:55 -07003126 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3127 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3128 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003129
John Kessenich5d610ee2018-03-07 18:05:55 -07003130 // built-in variable decorations
3131 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3132 if (builtIn != spv::BuiltInMax)
3133 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003134
John Kessenich5611c6d2018-04-05 11:25:02 -06003135 // nonuniform
3136 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3137
John Kessenichead86222018-03-28 18:01:20 -06003138 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3139 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3140 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3141 memberQualifier.semanticName);
3142 }
3143
chaoc771d89f2017-01-13 01:10:53 -08003144#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003145 if (builtIn == spv::BuiltInLayer) {
3146 // SPV_NV_viewport_array2 extension
3147 if (glslangMember.getQualifier().layoutViewportRelative){
3148 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3149 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3150 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003151 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003152 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3153 builder.addMemberDecoration(spvType, member,
3154 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3155 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3156 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3157 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003158 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003159 }
3160 if (glslangMember.getQualifier().layoutPassthrough) {
3161 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3162 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3163 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3164 }
chaoc771d89f2017-01-13 01:10:53 -08003165#endif
John Kessenich6090df02016-06-30 21:18:02 -06003166 }
3167
3168 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003169 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3170 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003171 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3172 builder.addCapability(spv::CapabilityGeometryStreams);
3173 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3174 }
John Kessenich6090df02016-06-30 21:18:02 -06003175}
3176
John Kessenich6c292d32016-02-15 20:58:50 -07003177// Turn the expression forming the array size into an id.
3178// This is not quite trivial, because of specialization constants.
3179// Sometimes, a raw constant is turned into an Id, and sometimes
3180// a specialization constant expression is.
3181spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3182{
3183 // First, see if this is sized with a node, meaning a specialization constant:
3184 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3185 if (specNode != nullptr) {
3186 builder.clearAccessChain();
3187 specNode->traverse(this);
3188 return accessChainLoad(specNode->getAsTyped()->getType());
3189 }
qining25262b32016-05-06 17:25:16 -04003190
John Kessenich6c292d32016-02-15 20:58:50 -07003191 // Otherwise, need a compile-time (front end) size, get it:
3192 int size = arraySizes.getDimSize(dim);
3193 assert(size > 0);
3194 return builder.makeUintConstant(size);
3195}
3196
John Kessenich103bef92016-02-08 21:38:15 -07003197// Wrap the builder's accessChainLoad to:
3198// - localize handling of RelaxedPrecision
3199// - use the SPIR-V inferred type instead of another conversion of the glslang type
3200// (avoids unnecessary work and possible type punning for structures)
3201// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003202spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3203{
John Kessenich103bef92016-02-08 21:38:15 -07003204 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003205
3206 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3207 coherentFlags |= TranslateCoherent(type);
3208
John Kessenich5611c6d2018-04-05 11:25:02 -06003209 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003210 TranslateNonUniformDecoration(type.getQualifier()),
3211 nominalTypeId,
3212 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3213 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003214
3215 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003216 if (type.getBasicType() == glslang::EbtBool) {
3217 if (builder.isScalarType(nominalTypeId)) {
3218 // Conversion for bool
3219 spv::Id boolType = builder.makeBoolType();
3220 if (nominalTypeId != boolType)
3221 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3222 } else if (builder.isVectorType(nominalTypeId)) {
3223 // Conversion for bvec
3224 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3225 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3226 if (nominalTypeId != bvecType)
3227 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3228 }
3229 }
John Kessenich103bef92016-02-08 21:38:15 -07003230
3231 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003232}
3233
Rex Xu27253232016-02-23 17:51:09 +08003234// Wrap the builder's accessChainStore to:
3235// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003236//
3237// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003238void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3239{
3240 // Need to convert to abstract types when necessary
3241 if (type.getBasicType() == glslang::EbtBool) {
3242 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3243
3244 if (builder.isScalarType(nominalTypeId)) {
3245 // Conversion for bool
3246 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003247 if (nominalTypeId != boolType) {
3248 // keep these outside arguments, for determinant order-of-evaluation
3249 spv::Id one = builder.makeUintConstant(1);
3250 spv::Id zero = builder.makeUintConstant(0);
3251 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3252 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003253 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003254 } else if (builder.isVectorType(nominalTypeId)) {
3255 // Conversion for bvec
3256 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3257 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003258 if (nominalTypeId != bvecType) {
3259 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003260 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3261 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3262 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003263 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003264 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3265 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003266 }
3267 }
3268
Jeff Bolz36831c92018-09-05 10:11:41 -05003269 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3270 coherentFlags |= TranslateCoherent(type);
3271
3272 builder.accessChainStore(rvalue,
3273 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3274 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003275}
3276
John Kessenich4bf71552016-09-02 11:20:21 -06003277// For storing when types match at the glslang level, but not might match at the
3278// SPIR-V level.
3279//
3280// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003281// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003282// as in a member-decorated way.
3283//
3284// NOTE: This function can handle any store request; if it's not special it
3285// simplifies to a simple OpStore.
3286//
3287// Implicitly uses the existing builder.accessChain as the storage target.
3288void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3289{
John Kessenichb3e24e42016-09-11 12:33:43 -06003290 // we only do the complex path here if it's an aggregate
3291 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003292 accessChainStore(type, rValue);
3293 return;
3294 }
3295
John Kessenichb3e24e42016-09-11 12:33:43 -06003296 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003297 spv::Id rType = builder.getTypeId(rValue);
3298 spv::Id lValue = builder.accessChainGetLValue();
3299 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3300 if (lType == rType) {
3301 accessChainStore(type, rValue);
3302 return;
3303 }
3304
John Kessenichb3e24e42016-09-11 12:33:43 -06003305 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003306 // where the two types were the same type in GLSL. This requires member
3307 // by member copy, recursively.
3308
John Kessenichb3e24e42016-09-11 12:33:43 -06003309 // If an array, copy element by element.
3310 if (type.isArray()) {
3311 glslang::TType glslangElementType(type, 0);
3312 spv::Id elementRType = builder.getContainedTypeId(rType);
3313 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3314 // get the source member
3315 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003316
John Kessenichb3e24e42016-09-11 12:33:43 -06003317 // set up the target storage
3318 builder.clearAccessChain();
3319 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003320 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003321
John Kessenichb3e24e42016-09-11 12:33:43 -06003322 // store the member
3323 multiTypeStore(glslangElementType, elementRValue);
3324 }
3325 } else {
3326 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003327
John Kessenichb3e24e42016-09-11 12:33:43 -06003328 // loop over structure members
3329 const glslang::TTypeList& members = *type.getStruct();
3330 for (int m = 0; m < (int)members.size(); ++m) {
3331 const glslang::TType& glslangMemberType = *members[m].type;
3332
3333 // get the source member
3334 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3335 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3336
3337 // set up the target storage
3338 builder.clearAccessChain();
3339 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003340 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003341
3342 // store the member
3343 multiTypeStore(glslangMemberType, memberRValue);
3344 }
John Kessenich4bf71552016-09-02 11:20:21 -06003345 }
3346}
3347
John Kessenichf85e8062015-12-19 13:57:10 -07003348// Decide whether or not this type should be
3349// decorated with offsets and strides, and if so
3350// whether std140 or std430 rules should be applied.
3351glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003352{
John Kessenichf85e8062015-12-19 13:57:10 -07003353 // has to be a block
3354 if (type.getBasicType() != glslang::EbtBlock)
3355 return glslang::ElpNone;
3356
Chao Chen3c366992018-09-19 11:41:59 -07003357 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003358 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003359 type.getQualifier().storage != glslang::EvqBuffer &&
3360 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003361 return glslang::ElpNone;
3362
3363 // return the layout to use
3364 switch (type.getQualifier().layoutPacking) {
3365 case glslang::ElpStd140:
3366 case glslang::ElpStd430:
3367 return type.getQualifier().layoutPacking;
3368 default:
3369 return glslang::ElpNone;
3370 }
John Kessenich31ed4832015-09-09 17:51:38 -06003371}
3372
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003373// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003374int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003375{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003376 int size;
John Kessenich49987892015-12-29 17:11:44 -07003377 int stride;
3378 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003379
3380 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003381}
3382
John Kessenich49987892015-12-29 17:11:44 -07003383// 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 -07003384// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003385int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003386{
John Kessenich49987892015-12-29 17:11:44 -07003387 glslang::TType elementType;
3388 elementType.shallowCopy(matrixType);
3389 elementType.clearArraySizes();
3390
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003391 int size;
John Kessenich49987892015-12-29 17:11:44 -07003392 int stride;
3393 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3394
3395 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003396}
3397
John Kessenich5e4b1242015-08-06 22:53:06 -06003398// Given a member type of a struct, realign the current offset for it, and compute
3399// the next (not yet aligned) offset for the next member, which will get aligned
3400// on the next call.
3401// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3402// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3403// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003404void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003405 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003406{
3407 // this will get a positive value when deemed necessary
3408 nextOffset = -1;
3409
John Kessenich5e4b1242015-08-06 22:53:06 -06003410 // override anything in currentOffset with user-set offset
3411 if (memberType.getQualifier().hasOffset())
3412 currentOffset = memberType.getQualifier().layoutOffset;
3413
3414 // It could be that current linker usage in glslang updated all the layoutOffset,
3415 // in which case the following code does not matter. But, that's not quite right
3416 // once cross-compilation unit GLSL validation is done, as the original user
3417 // settings are needed in layoutOffset, and then the following will come into play.
3418
John Kessenichf85e8062015-12-19 13:57:10 -07003419 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003420 if (! memberType.getQualifier().hasOffset())
3421 currentOffset = -1;
3422
3423 return;
3424 }
3425
John Kessenichf85e8062015-12-19 13:57:10 -07003426 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 if (currentOffset < 0)
3428 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003429
John Kessenich5e4b1242015-08-06 22:53:06 -06003430 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3431 // but possibly not yet correctly aligned.
3432
3433 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003434 int dummyStride;
3435 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003436
3437 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003438 // TODO: make this consistent in early phases of code:
3439 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3440 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3441 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003442 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003443 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003444 int dummySize;
3445 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3446 if (componentAlignment <= 4)
3447 memberAlignment = componentAlignment;
3448 }
3449
3450 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003451 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003452
3453 // Bump up to vec4 if there is a bad straddle
3454 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3455 glslang::RoundToPow2(currentOffset, 16);
3456
John Kessenich5e4b1242015-08-06 22:53:06 -06003457 nextOffset = currentOffset + memberSize;
3458}
3459
David Netoa901ffe2016-06-08 14:11:40 +01003460void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003461{
David Netoa901ffe2016-06-08 14:11:40 +01003462 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3463 switch (glslangBuiltIn)
3464 {
3465 case glslang::EbvClipDistance:
3466 case glslang::EbvCullDistance:
3467 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003468#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003469 case glslang::EbvViewportMaskNV:
3470 case glslang::EbvSecondaryPositionNV:
3471 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003472 case glslang::EbvPositionPerViewNV:
3473 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003474 case glslang::EbvTaskCountNV:
3475 case glslang::EbvPrimitiveCountNV:
3476 case glslang::EbvPrimitiveIndicesNV:
3477 case glslang::EbvClipDistancePerViewNV:
3478 case glslang::EbvCullDistancePerViewNV:
3479 case glslang::EbvLayerPerViewNV:
3480 case glslang::EbvMeshViewCountNV:
3481 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003482#endif
David Netoa901ffe2016-06-08 14:11:40 +01003483 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3484 // Alternately, we could just call this for any glslang built-in, since the
3485 // capability already guards against duplicates.
3486 TranslateBuiltInDecoration(glslangBuiltIn, false);
3487 break;
3488 default:
3489 // Capabilities were already generated when the struct was declared.
3490 break;
3491 }
John Kessenichebb50532016-05-16 19:22:05 -06003492}
3493
John Kessenich6fccb3c2016-09-19 16:01:41 -06003494bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003495{
John Kessenicheee9d532016-09-19 18:09:30 -06003496 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003497}
3498
John Kessenichd41993d2017-09-10 15:21:05 -06003499// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003500// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3501// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003502bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003503{
John Kessenich6a14f782017-12-04 02:48:10 -07003504 assert(qualifier == glslang::EvqIn ||
3505 qualifier == glslang::EvqOut ||
3506 qualifier == glslang::EvqInOut ||
3507 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003508 return qualifier != glslang::EvqConstReadOnly;
3509}
3510
3511// Is parameter pass-by-original?
3512bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3513 bool implicitThisParam)
3514{
3515 if (implicitThisParam) // implicit this
3516 return true;
3517 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003518 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003519 return paramType.containsOpaque() || // sampler, etc.
3520 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3521}
3522
John Kessenich140f3df2015-06-26 16:58:36 -06003523// Make all the functions, skeletally, without actually visiting their bodies.
3524void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3525{
Jeff Bolz36831c92018-09-05 10:11:41 -05003526 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003527 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3528 if (paramPrecision != spv::NoPrecision)
3529 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003530 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003531 };
3532
John Kessenich140f3df2015-06-26 16:58:36 -06003533 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3534 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003535 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003536 continue;
3537
3538 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003539 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003540 //
qining25262b32016-05-06 17:25:16 -04003541 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003542 // function. What it is an address of varies:
3543 //
John Kessenich4bf71552016-09-02 11:20:21 -06003544 // - "in" parameters not marked as "const" can be written to without modifying the calling
3545 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003546 //
3547 // - "const in" parameters can just be the r-value, as no writes need occur.
3548 //
John Kessenich4bf71552016-09-02 11:20:21 -06003549 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3550 // 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 -06003551
3552 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003553 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003554 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3555
John Kessenichfad62972017-07-18 02:35:46 -06003556 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3557 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003558
John Kessenichfad62972017-07-18 02:35:46 -06003559 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003560 for (int p = 0; p < (int)parameters.size(); ++p) {
3561 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3562 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003563 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003564 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003565 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003566 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3567 else
John Kessenich4bf71552016-09-02 11:20:21 -06003568 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003569 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003570 paramTypes.push_back(typeId);
3571 }
3572
3573 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003574 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3575 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003576 glslFunction->getName().c_str(), paramTypes,
3577 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003578 if (implicitThis)
3579 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003580
3581 // Track function to emit/call later
3582 functionMap[glslFunction->getName().c_str()] = function;
3583
3584 // Set the parameter id's
3585 for (int p = 0; p < (int)parameters.size(); ++p) {
3586 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3587 // give a name too
3588 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3589 }
3590 }
3591}
3592
3593// Process all the initializers, while skipping the functions and link objects
3594void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3595{
3596 builder.setBuildPoint(shaderEntry->getLastBlock());
3597 for (int i = 0; i < (int)initializers.size(); ++i) {
3598 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3599 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3600
3601 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003602 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003603 initializer->traverse(this);
3604 }
3605 }
3606}
3607
3608// Process all the functions, while skipping initializers.
3609void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3610{
3611 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3612 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003613 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003614 node->traverse(this);
3615 }
3616}
3617
3618void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3619{
qining25262b32016-05-06 17:25:16 -04003620 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003621 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003622 currentFunction = functionMap[node->getName().c_str()];
3623 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003624 builder.setBuildPoint(functionBlock);
3625}
3626
Rex Xu04db3f52015-09-16 11:44:02 +08003627void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003628{
Rex Xufc618912015-09-09 16:42:49 +08003629 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003630
3631 glslang::TSampler sampler = {};
3632 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003633#ifdef AMD_EXTENSIONS
3634 bool f16ShadowCompare = false;
3635#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003636 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003637 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3638 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003639#ifdef AMD_EXTENSIONS
3640 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3641#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003642 }
3643
John Kessenich140f3df2015-06-26 16:58:36 -06003644 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3645 builder.clearAccessChain();
3646 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003647
3648 // Special case l-value operands
3649 bool lvalue = false;
3650 switch (node.getOp()) {
3651 case glslang::EOpImageAtomicAdd:
3652 case glslang::EOpImageAtomicMin:
3653 case glslang::EOpImageAtomicMax:
3654 case glslang::EOpImageAtomicAnd:
3655 case glslang::EOpImageAtomicOr:
3656 case glslang::EOpImageAtomicXor:
3657 case glslang::EOpImageAtomicExchange:
3658 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003659 case glslang::EOpImageAtomicLoad:
3660 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003661 if (i == 0)
3662 lvalue = true;
3663 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003664 case glslang::EOpSparseImageLoad:
3665 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3666 lvalue = true;
3667 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003668#ifdef AMD_EXTENSIONS
3669 case glslang::EOpSparseTexture:
3670 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3671 lvalue = true;
3672 break;
3673 case glslang::EOpSparseTextureClamp:
3674 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3675 lvalue = true;
3676 break;
3677 case glslang::EOpSparseTextureLod:
3678 case glslang::EOpSparseTextureOffset:
3679 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3680 lvalue = true;
3681 break;
3682#else
Rex Xu48edadf2015-12-31 16:11:41 +08003683 case glslang::EOpSparseTexture:
3684 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3685 lvalue = true;
3686 break;
3687 case glslang::EOpSparseTextureClamp:
3688 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3689 lvalue = true;
3690 break;
3691 case glslang::EOpSparseTextureLod:
3692 case glslang::EOpSparseTextureOffset:
3693 if (i == 3)
3694 lvalue = true;
3695 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003696#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003697 case glslang::EOpSparseTextureFetch:
3698 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3699 lvalue = true;
3700 break;
3701 case glslang::EOpSparseTextureFetchOffset:
3702 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3703 lvalue = true;
3704 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003705#ifdef AMD_EXTENSIONS
3706 case glslang::EOpSparseTextureLodOffset:
3707 case glslang::EOpSparseTextureGrad:
3708 case glslang::EOpSparseTextureOffsetClamp:
3709 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3710 lvalue = true;
3711 break;
3712 case glslang::EOpSparseTextureGradOffset:
3713 case glslang::EOpSparseTextureGradClamp:
3714 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3715 lvalue = true;
3716 break;
3717 case glslang::EOpSparseTextureGradOffsetClamp:
3718 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3719 lvalue = true;
3720 break;
3721#else
Rex Xu48edadf2015-12-31 16:11:41 +08003722 case glslang::EOpSparseTextureLodOffset:
3723 case glslang::EOpSparseTextureGrad:
3724 case glslang::EOpSparseTextureOffsetClamp:
3725 if (i == 4)
3726 lvalue = true;
3727 break;
3728 case glslang::EOpSparseTextureGradOffset:
3729 case glslang::EOpSparseTextureGradClamp:
3730 if (i == 5)
3731 lvalue = true;
3732 break;
3733 case glslang::EOpSparseTextureGradOffsetClamp:
3734 if (i == 6)
3735 lvalue = true;
3736 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003737#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003738 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003739 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3740 lvalue = true;
3741 break;
3742 case glslang::EOpSparseTextureGatherOffset:
3743 case glslang::EOpSparseTextureGatherOffsets:
3744 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3745 lvalue = true;
3746 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003747#ifdef AMD_EXTENSIONS
3748 case glslang::EOpSparseTextureGatherLod:
3749 if (i == 3)
3750 lvalue = true;
3751 break;
3752 case glslang::EOpSparseTextureGatherLodOffset:
3753 case glslang::EOpSparseTextureGatherLodOffsets:
3754 if (i == 4)
3755 lvalue = true;
3756 break;
Rex Xu129799a2017-07-05 17:23:28 +08003757 case glslang::EOpSparseImageLoadLod:
3758 if (i == 3)
3759 lvalue = true;
3760 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003761#endif
Chao Chen3a137962018-09-19 11:41:27 -07003762#ifdef NV_EXTENSIONS
3763 case glslang::EOpImageSampleFootprintNV:
3764 if (i == 4)
3765 lvalue = true;
3766 break;
3767 case glslang::EOpImageSampleFootprintClampNV:
3768 case glslang::EOpImageSampleFootprintLodNV:
3769 if (i == 5)
3770 lvalue = true;
3771 break;
3772 case glslang::EOpImageSampleFootprintGradNV:
3773 if (i == 6)
3774 lvalue = true;
3775 break;
3776 case glslang::EOpImageSampleFootprintGradClampNV:
3777 if (i == 7)
3778 lvalue = true;
3779 break;
3780#endif
Rex Xufc618912015-09-09 16:42:49 +08003781 default:
3782 break;
3783 }
3784
Rex Xu6b86d492015-09-16 17:48:22 +08003785 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003786 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003787 else
John Kessenich32cfd492016-02-02 12:37:46 -07003788 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003789 }
3790}
3791
John Kessenichfc51d282015-08-19 13:34:18 -06003792void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003793{
John Kessenichfc51d282015-08-19 13:34:18 -06003794 builder.clearAccessChain();
3795 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003796 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003797}
John Kessenich140f3df2015-06-26 16:58:36 -06003798
John Kessenichfc51d282015-08-19 13:34:18 -06003799spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3800{
John Kesseniche485c7a2017-05-31 18:50:53 -06003801 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003802 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003803
3804 builder.setLine(node->getLoc().line);
3805
John Kessenichfc51d282015-08-19 13:34:18 -06003806 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003807
3808 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3809 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3810 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003811#ifdef AMD_EXTENSIONS
3812 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3813 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3814 : false;
3815#endif
3816
John Kessenichfc51d282015-08-19 13:34:18 -06003817 std::vector<spv::Id> arguments;
3818 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003819 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003820 else
3821 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003822 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003823
3824 spv::Builder::TextureParameters params = { };
3825 params.sampler = arguments[0];
3826
Rex Xu04db3f52015-09-16 11:44:02 +08003827 glslang::TCrackedTextureOp cracked;
3828 node->crackTexture(sampler, cracked);
3829
amhagan05506bb2017-06-13 16:53:02 -04003830 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003831
John Kessenichfc51d282015-08-19 13:34:18 -06003832 // Check for queries
3833 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003834 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3835 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003836 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003837
John Kessenichfc51d282015-08-19 13:34:18 -06003838 switch (node->getOp()) {
3839 case glslang::EOpImageQuerySize:
3840 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003841 if (arguments.size() > 1) {
3842 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003843 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003845 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003846 case glslang::EOpImageQuerySamples:
3847 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003848 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003849 case glslang::EOpTextureQueryLod:
3850 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003851 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003852 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003853 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003854 case glslang::EOpSparseTexelsResident:
3855 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003856 default:
3857 assert(0);
3858 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003859 }
John Kessenich140f3df2015-06-26 16:58:36 -06003860 }
3861
LoopDawg4425f242018-02-18 11:40:01 -07003862 int components = node->getType().getVectorSize();
3863
3864 if (node->getOp() == glslang::EOpTextureFetch) {
3865 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3866 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3867 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3868 // here around e.g. which ones return scalars or other types.
3869 components = 4;
3870 }
3871
3872 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3873
3874 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3875
Rex Xufc618912015-09-09 16:42:49 +08003876 // Check for image functions other than queries
3877 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003878 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003879 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003880 spv::IdImmediate image = { true, *(opIt++) };
3881 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003882
3883 // Handle subpass operations
3884 // TODO: GLSL should change to have the "MS" only on the type rather than the
3885 // built-in function.
3886 if (cracked.subpass) {
3887 // add on the (0,0) coordinate
3888 spv::Id zero = builder.makeIntConstant(0);
3889 std::vector<spv::Id> comps;
3890 comps.push_back(zero);
3891 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003892 spv::IdImmediate coord = { true,
3893 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3894 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003895 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003896 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3897 operands.push_back(imageOperands);
3898 spv::IdImmediate imageOperand = { true, *(opIt++) };
3899 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003900 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003901 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3902 builder.setPrecision(result, precision);
3903 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003904 }
3905
John Kessenich149afc32018-08-14 13:31:43 -06003906 spv::IdImmediate coord = { true, *(opIt++) };
3907 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003908#ifdef AMD_EXTENSIONS
3909 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3910#else
John Kessenich56bab042015-09-16 10:54:31 -06003911 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003912#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003913 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003914 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003915 mask = mask | spv::ImageOperandsSampleMask;
3916 }
Rex Xu129799a2017-07-05 17:23:28 +08003917#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003918 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003919 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3920 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003921 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003922 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003923#endif
3924 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3925 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3926 if (mask) {
3927 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3928 operands.push_back(imageOperands);
3929 }
3930 if (mask & spv::ImageOperandsSampleMask) {
3931 spv::IdImmediate imageOperand = { true, *opIt++ };
3932 operands.push_back(imageOperand);
3933 }
3934#ifdef AMD_EXTENSIONS
3935 if (mask & spv::ImageOperandsLodMask) {
3936 spv::IdImmediate imageOperand = { true, *opIt++ };
3937 operands.push_back(imageOperand);
3938 }
3939#endif
3940 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3941 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3942 operands.push_back(imageOperand);
3943 }
3944
John Kessenich149afc32018-08-14 13:31:43 -06003945 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003946 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003947
John Kessenich149afc32018-08-14 13:31:43 -06003948 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003949 builder.setPrecision(result[0], precision);
3950
3951 // If needed, add a conversion constructor to the proper size.
3952 if (components != node->getType().getVectorSize())
3953 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3954
3955 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003956#ifdef AMD_EXTENSIONS
3957 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3958#else
John Kessenich56bab042015-09-16 10:54:31 -06003959 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003960#endif
Rex Xu129799a2017-07-05 17:23:28 +08003961
Jeff Bolz36831c92018-09-05 10:11:41 -05003962 // Push the texel value before the operands
3963#ifdef AMD_EXTENSIONS
3964 if (sampler.ms || cracked.lod) {
3965#else
3966 if (sampler.ms) {
3967#endif
John Kessenich149afc32018-08-14 13:31:43 -06003968 spv::IdImmediate texel = { true, *(opIt + 1) };
3969 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06003970 } else {
3971 spv::IdImmediate texel = { true, *opIt };
3972 operands.push_back(texel);
3973 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003974
3975 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
3976 if (sampler.ms) {
3977 mask = mask | spv::ImageOperandsSampleMask;
3978 }
3979#ifdef AMD_EXTENSIONS
3980 if (cracked.lod) {
3981 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3982 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3983 mask = mask | spv::ImageOperandsLodMask;
3984 }
3985#endif
3986 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3987 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
3988 if (mask) {
3989 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3990 operands.push_back(imageOperands);
3991 }
3992 if (mask & spv::ImageOperandsSampleMask) {
3993 spv::IdImmediate imageOperand = { true, *opIt++ };
3994 operands.push_back(imageOperand);
3995 }
3996#ifdef AMD_EXTENSIONS
3997 if (mask & spv::ImageOperandsLodMask) {
3998 spv::IdImmediate imageOperand = { true, *opIt++ };
3999 operands.push_back(imageOperand);
4000 }
4001#endif
4002 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4003 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4004 operands.push_back(imageOperand);
4005 }
4006
John Kessenich56bab042015-09-16 10:54:31 -06004007 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004008 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004009 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004010 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004011#ifdef AMD_EXTENSIONS
4012 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4013#else
Rex Xu5eafa472016-02-19 22:24:03 +08004014 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004015#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004016 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004017 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004018 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4019
Jeff Bolz36831c92018-09-05 10:11:41 -05004020 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004021 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004022 mask = mask | spv::ImageOperandsSampleMask;
4023 }
Rex Xu129799a2017-07-05 17:23:28 +08004024#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004025 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004026 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4027 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4028
Jeff Bolz36831c92018-09-05 10:11:41 -05004029 mask = mask | spv::ImageOperandsLodMask;
4030 }
4031#endif
4032 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4033 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4034 if (mask) {
4035 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004036 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004037 }
4038 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004039 spv::IdImmediate imageOperand = { true, *opIt++ };
4040 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004041 }
4042#ifdef AMD_EXTENSIONS
4043 if (mask & spv::ImageOperandsLodMask) {
4044 spv::IdImmediate imageOperand = { true, *opIt++ };
4045 operands.push_back(imageOperand);
4046 }
Rex Xu129799a2017-07-05 17:23:28 +08004047#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004048 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4049 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4050 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004051 }
4052
4053 // Create the return type that was a special structure
4054 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004055 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004056 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4057 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4058
4059 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4060
4061 // Decode the return type
4062 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4063 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004064 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004065 // Process image atomic operations
4066
4067 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4068 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004069 // For non-MS, the sample value should be 0
4070 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4071 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004072
Jeff Bolz36831c92018-09-05 10:11:41 -05004073 spv::Id resultTypeId;
4074 // imageAtomicStore has a void return type so base the pointer type on
4075 // the type of the value operand.
4076 if (node->getOp() == glslang::EOpImageAtomicStore) {
4077 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4078 } else {
4079 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4080 }
John Kessenich56bab042015-09-16 10:54:31 -06004081 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004082
4083 std::vector<spv::Id> operands;
4084 operands.push_back(pointer);
4085 for (; opIt != arguments.end(); ++opIt)
4086 operands.push_back(*opIt);
4087
John Kessenich8c8505c2016-07-26 12:50:38 -06004088 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004089 }
4090 }
4091
amhagan05506bb2017-06-13 16:53:02 -04004092#ifdef AMD_EXTENSIONS
4093 // Check for fragment mask functions other than queries
4094 if (cracked.fragMask) {
4095 assert(sampler.ms);
4096
4097 auto opIt = arguments.begin();
4098 std::vector<spv::Id> operands;
4099
4100 // Extract the image if necessary
4101 if (builder.isSampledImage(params.sampler))
4102 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4103
4104 operands.push_back(params.sampler);
4105 ++opIt;
4106
4107 if (sampler.isSubpass()) {
4108 // add on the (0,0) coordinate
4109 spv::Id zero = builder.makeIntConstant(0);
4110 std::vector<spv::Id> comps;
4111 comps.push_back(zero);
4112 comps.push_back(zero);
4113 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4114 }
4115
4116 for (; opIt != arguments.end(); ++opIt)
4117 operands.push_back(*opIt);
4118
4119 spv::Op fragMaskOp = spv::OpNop;
4120 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4121 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4122 else if (node->getOp() == glslang::EOpFragmentFetch)
4123 fragMaskOp = spv::OpFragmentFetchAMD;
4124
4125 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4126 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4127 return builder.createOp(fragMaskOp, resultType(), operands);
4128 }
4129#endif
4130
Rex Xufc618912015-09-09 16:42:49 +08004131 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004132 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004133#ifdef NV_EXTENSIONS
4134 bool imageFootprint = node->isImageFootprint();
4135#endif
4136
Rex Xu71519fe2015-11-11 15:35:47 +08004137 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4138
John Kessenichfc51d282015-08-19 13:34:18 -06004139 // check for bias argument
4140 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004141#ifdef AMD_EXTENSIONS
4142 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4143#else
Rex Xu71519fe2015-11-11 15:35:47 +08004144 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004145#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004146 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004147#ifdef AMD_EXTENSIONS
4148 if (cracked.gather)
4149 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004150
4151 if (f16ShadowCompare)
4152 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004153#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004154 if (cracked.offset)
4155 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004156#ifdef AMD_EXTENSIONS
4157 else if (cracked.offsets)
4158 ++nonBiasArgCount;
4159#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004160 if (cracked.grad)
4161 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004162 if (cracked.lodClamp)
4163 ++nonBiasArgCount;
4164 if (sparse)
4165 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004166#ifdef NV_EXTENSIONS
4167 if (imageFootprint)
4168 //Following three extra arguments
4169 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4170 nonBiasArgCount += 3;
4171#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004172 if ((int)arguments.size() > nonBiasArgCount)
4173 bias = true;
4174 }
4175
John Kessenicha5c33d62016-06-02 23:45:21 -06004176 // See if the sampler param should really be just the SPV image part
4177 if (cracked.fetch) {
4178 // a fetch needs to have the image extracted first
4179 if (builder.isSampledImage(params.sampler))
4180 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4181 }
4182
Rex Xu225e0fc2016-11-17 17:47:59 +08004183#ifdef AMD_EXTENSIONS
4184 if (cracked.gather) {
4185 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4186 if (bias || cracked.lod ||
4187 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4188 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004189 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004190 }
4191 }
4192#endif
4193
John Kessenichfc51d282015-08-19 13:34:18 -06004194 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004195
John Kessenichfc51d282015-08-19 13:34:18 -06004196 params.coords = arguments[1];
4197 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004198 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004199
4200 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004201#ifdef AMD_EXTENSIONS
4202 if (cubeCompare || f16ShadowCompare) {
4203#else
Rex Xu48edadf2015-12-31 16:11:41 +08004204 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004205#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004206 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004207 ++extraArgs;
4208 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004209 params.Dref = arguments[2];
4210 ++extraArgs;
4211 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004212 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004213 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004214 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004215 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004216 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004217 dRefComp = builder.getNumComponents(params.coords) - 1;
4218 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004219 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4220 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004221
4222 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004223 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004224 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004225 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004226 } else if (glslangIntermediate->getStage() != EShLangFragment
4227#ifdef NV_EXTENSIONS
4228 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4229 && !(glslangIntermediate->getStage() == EShLangCompute &&
4230 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4231#endif
4232 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004233 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4234 noImplicitLod = true;
4235 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004236
4237 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004238 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004239 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004240 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004241 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004242
4243 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004244 if (cracked.grad) {
4245 params.gradX = arguments[2 + extraArgs];
4246 params.gradY = arguments[3 + extraArgs];
4247 extraArgs += 2;
4248 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004249
4250 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004251 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004252 params.offset = arguments[2 + extraArgs];
4253 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004254 } else if (cracked.offsets) {
4255 params.offsets = arguments[2 + extraArgs];
4256 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004257 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004258
4259 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004260 if (cracked.lodClamp) {
4261 params.lodClamp = arguments[2 + extraArgs];
4262 ++extraArgs;
4263 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004264 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004265 if (sparse) {
4266 params.texelOut = arguments[2 + extraArgs];
4267 ++extraArgs;
4268 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004269
John Kessenich76d4dfc2016-06-16 12:43:23 -06004270 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004271 if (cracked.gather && ! sampler.shadow) {
4272 // default component is 0, if missing, otherwise an argument
4273 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004274 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004275 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004276 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004277 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004278 }
Chao Chen3a137962018-09-19 11:41:27 -07004279#ifdef NV_EXTENSIONS
4280 spv::Id resultStruct = spv::NoResult;
4281 if (imageFootprint) {
4282 //Following three extra arguments
4283 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4284 params.granularity = arguments[2 + extraArgs];
4285 params.coarse = arguments[3 + extraArgs];
4286 resultStruct = arguments[4 + extraArgs];
4287 extraArgs += 3;
4288 }
4289#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004290 // bias
4291 if (bias) {
4292 params.bias = arguments[2 + extraArgs];
4293 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004294 }
John Kessenichfc51d282015-08-19 13:34:18 -06004295
Chao Chen3a137962018-09-19 11:41:27 -07004296#ifdef NV_EXTENSIONS
4297 if (imageFootprint) {
4298 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4299 builder.addCapability(spv::CapabilityImageFootprintNV);
4300
4301
4302 //resultStructType(OpenGL type) contains 5 elements:
4303 //struct gl_TextureFootprint2DNV {
4304 // uvec2 anchor;
4305 // uvec2 offset;
4306 // uvec2 mask;
4307 // uint lod;
4308 // uint granularity;
4309 //};
4310 //or
4311 //struct gl_TextureFootprint3DNV {
4312 // uvec3 anchor;
4313 // uvec3 offset;
4314 // uvec2 mask;
4315 // uint lod;
4316 // uint granularity;
4317 //};
4318 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4319 assert(builder.isStructType(resultStructType));
4320
4321 //resType (SPIR-V type) contains 6 elements:
4322 //Member 0 must be a Boolean type scalar(LOD),
4323 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4324 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4325 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4326 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4327 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4328 std::vector<spv::Id> members;
4329 members.push_back(resultType());
4330 for (int i = 0; i < 5; i++) {
4331 members.push_back(builder.getContainedTypeId(resultStructType, i));
4332 }
4333 spv::Id resType = builder.makeStructType(members, "ResType");
4334
4335 //call ImageFootprintNV
4336 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4337
4338 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4339 for (int i = 0; i < 5; i++) {
4340 builder.clearAccessChain();
4341 builder.setAccessChainLValue(resultStruct);
4342
4343 //Accessing to a struct we created, no coherent flag is set
4344 spv::Builder::AccessChain::CoherentFlags flags;
4345 flags.clear();
4346
4347 builder.accessChainPush(builder.makeIntConstant(i), flags);
4348 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4349 }
4350 return builder.createCompositeExtract(res, resultType(), 0);
4351 }
4352#endif
4353
John Kessenich65336482016-06-16 14:06:26 -06004354 // projective component (might not to move)
4355 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4356 // are divided by the last component of P."
4357 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4358 // unused components will appear after all used components."
4359 if (cracked.proj) {
4360 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4361 int projTargetComp;
4362 switch (sampler.dim) {
4363 case glslang::Esd1D: projTargetComp = 1; break;
4364 case glslang::Esd2D: projTargetComp = 2; break;
4365 case glslang::EsdRect: projTargetComp = 2; break;
4366 default: projTargetComp = projSourceComp; break;
4367 }
4368 // copy the projective coordinate if we have to
4369 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004370 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004371 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4372 projSourceComp);
4373 params.coords = builder.createCompositeInsert(projComp, params.coords,
4374 builder.getTypeId(params.coords), projTargetComp);
4375 }
4376 }
4377
Jeff Bolz36831c92018-09-05 10:11:41 -05004378 // nonprivate
4379 if (imageType.getQualifier().nonprivate) {
4380 params.nonprivate = true;
4381 }
4382
4383 // volatile
4384 if (imageType.getQualifier().volatil) {
4385 params.volatil = true;
4386 }
4387
St0fFa1184dd2018-04-09 21:08:14 +02004388 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004389 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004390 );
LoopDawg4425f242018-02-18 11:40:01 -07004391
4392 if (components != node->getType().getVectorSize())
4393 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4394
4395 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004396}
4397
4398spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4399{
4400 // Grab the function's pointer from the previously created function
4401 spv::Function* function = functionMap[node->getName().c_str()];
4402 if (! function)
4403 return 0;
4404
4405 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4406 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4407
4408 // See comments in makeFunctions() for details about the semantics for parameter passing.
4409 //
4410 // These imply we need a four step process:
4411 // 1. Evaluate the arguments
4412 // 2. Allocate and make copies of in, out, and inout arguments
4413 // 3. Make the call
4414 // 4. Copy back the results
4415
John Kessenichd3ed90b2018-05-04 11:43:03 -06004416 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004417 std::vector<spv::Builder::AccessChain> lValues;
4418 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004419 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004420 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004421 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004422 // build l-value
4423 builder.clearAccessChain();
4424 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004425 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004426 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004427 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004428 // save l-value
4429 lValues.push_back(builder.getAccessChain());
4430 } else {
4431 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004432 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004433 }
4434 }
4435
4436 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4437 // copy the original into that space.
4438 //
4439 // Also, build up the list of actual arguments to pass in for the call
4440 int lValueCount = 0;
4441 int rValueCount = 0;
4442 std::vector<spv::Id> spvArgs;
4443 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4444 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004445 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004446 builder.setAccessChain(lValues[lValueCount]);
4447 arg = builder.accessChainGetLValue();
4448 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004449 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004450 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004451 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004452 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4453 // need to copy the input into output space
4454 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004455 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004456 builder.clearAccessChain();
4457 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004458 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004459 }
4460 ++lValueCount;
4461 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004462 // process r-value, which involves a copy for a type mismatch
4463 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4464 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4465 builder.clearAccessChain();
4466 builder.setAccessChainLValue(argCopy);
4467 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4468 arg = builder.createLoad(argCopy);
4469 } else
4470 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004471 ++rValueCount;
4472 }
4473 spvArgs.push_back(arg);
4474 }
4475
4476 // 3. Make the call.
4477 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004478 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004479
4480 // 4. Copy back out an "out" arguments.
4481 lValueCount = 0;
4482 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004483 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004484 ++lValueCount;
4485 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004486 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4487 spv::Id copy = builder.createLoad(spvArgs[a]);
4488 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004489 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004490 }
4491 ++lValueCount;
4492 }
4493 }
4494
4495 return result;
4496}
4497
4498// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004499spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004500 spv::Id typeId, spv::Id left, spv::Id right,
4501 glslang::TBasicType typeProxy, bool reduceComparison)
4502{
John Kessenich66011cb2018-03-06 16:12:04 -07004503 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4504 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004505 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004506
4507 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004508 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004509 bool comparison = false;
4510
4511 switch (op) {
4512 case glslang::EOpAdd:
4513 case glslang::EOpAddAssign:
4514 if (isFloat)
4515 binOp = spv::OpFAdd;
4516 else
4517 binOp = spv::OpIAdd;
4518 break;
4519 case glslang::EOpSub:
4520 case glslang::EOpSubAssign:
4521 if (isFloat)
4522 binOp = spv::OpFSub;
4523 else
4524 binOp = spv::OpISub;
4525 break;
4526 case glslang::EOpMul:
4527 case glslang::EOpMulAssign:
4528 if (isFloat)
4529 binOp = spv::OpFMul;
4530 else
4531 binOp = spv::OpIMul;
4532 break;
4533 case glslang::EOpVectorTimesScalar:
4534 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004535 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004536 if (builder.isVector(right))
4537 std::swap(left, right);
4538 assert(builder.isScalar(right));
4539 needMatchingVectors = false;
4540 binOp = spv::OpVectorTimesScalar;
4541 } else
4542 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004543 break;
4544 case glslang::EOpVectorTimesMatrix:
4545 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004546 binOp = spv::OpVectorTimesMatrix;
4547 break;
4548 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004549 binOp = spv::OpMatrixTimesVector;
4550 break;
4551 case glslang::EOpMatrixTimesScalar:
4552 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004553 binOp = spv::OpMatrixTimesScalar;
4554 break;
4555 case glslang::EOpMatrixTimesMatrix:
4556 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004557 binOp = spv::OpMatrixTimesMatrix;
4558 break;
4559 case glslang::EOpOuterProduct:
4560 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004561 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004562 break;
4563
4564 case glslang::EOpDiv:
4565 case glslang::EOpDivAssign:
4566 if (isFloat)
4567 binOp = spv::OpFDiv;
4568 else if (isUnsigned)
4569 binOp = spv::OpUDiv;
4570 else
4571 binOp = spv::OpSDiv;
4572 break;
4573 case glslang::EOpMod:
4574 case glslang::EOpModAssign:
4575 if (isFloat)
4576 binOp = spv::OpFMod;
4577 else if (isUnsigned)
4578 binOp = spv::OpUMod;
4579 else
4580 binOp = spv::OpSMod;
4581 break;
4582 case glslang::EOpRightShift:
4583 case glslang::EOpRightShiftAssign:
4584 if (isUnsigned)
4585 binOp = spv::OpShiftRightLogical;
4586 else
4587 binOp = spv::OpShiftRightArithmetic;
4588 break;
4589 case glslang::EOpLeftShift:
4590 case glslang::EOpLeftShiftAssign:
4591 binOp = spv::OpShiftLeftLogical;
4592 break;
4593 case glslang::EOpAnd:
4594 case glslang::EOpAndAssign:
4595 binOp = spv::OpBitwiseAnd;
4596 break;
4597 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004598 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004599 binOp = spv::OpLogicalAnd;
4600 break;
4601 case glslang::EOpInclusiveOr:
4602 case glslang::EOpInclusiveOrAssign:
4603 binOp = spv::OpBitwiseOr;
4604 break;
4605 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004606 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004607 binOp = spv::OpLogicalOr;
4608 break;
4609 case glslang::EOpExclusiveOr:
4610 case glslang::EOpExclusiveOrAssign:
4611 binOp = spv::OpBitwiseXor;
4612 break;
4613 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004614 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004615 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004616 break;
4617
4618 case glslang::EOpLessThan:
4619 case glslang::EOpGreaterThan:
4620 case glslang::EOpLessThanEqual:
4621 case glslang::EOpGreaterThanEqual:
4622 case glslang::EOpEqual:
4623 case glslang::EOpNotEqual:
4624 case glslang::EOpVectorEqual:
4625 case glslang::EOpVectorNotEqual:
4626 comparison = true;
4627 break;
4628 default:
4629 break;
4630 }
4631
John Kessenich7c1aa102015-10-15 13:29:11 -06004632 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004633 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004634 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004635 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004636 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004637
4638 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004639 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004640 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004641
qining25262b32016-05-06 17:25:16 -04004642 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004643 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004644 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004645 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004646 }
4647
4648 if (! comparison)
4649 return 0;
4650
John Kessenich7c1aa102015-10-15 13:29:11 -06004651 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004652
John Kessenich4583b612016-08-07 19:14:22 -06004653 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004654 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4655 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004656 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004657 return result;
4658 }
John Kessenich140f3df2015-06-26 16:58:36 -06004659
4660 switch (op) {
4661 case glslang::EOpLessThan:
4662 if (isFloat)
4663 binOp = spv::OpFOrdLessThan;
4664 else if (isUnsigned)
4665 binOp = spv::OpULessThan;
4666 else
4667 binOp = spv::OpSLessThan;
4668 break;
4669 case glslang::EOpGreaterThan:
4670 if (isFloat)
4671 binOp = spv::OpFOrdGreaterThan;
4672 else if (isUnsigned)
4673 binOp = spv::OpUGreaterThan;
4674 else
4675 binOp = spv::OpSGreaterThan;
4676 break;
4677 case glslang::EOpLessThanEqual:
4678 if (isFloat)
4679 binOp = spv::OpFOrdLessThanEqual;
4680 else if (isUnsigned)
4681 binOp = spv::OpULessThanEqual;
4682 else
4683 binOp = spv::OpSLessThanEqual;
4684 break;
4685 case glslang::EOpGreaterThanEqual:
4686 if (isFloat)
4687 binOp = spv::OpFOrdGreaterThanEqual;
4688 else if (isUnsigned)
4689 binOp = spv::OpUGreaterThanEqual;
4690 else
4691 binOp = spv::OpSGreaterThanEqual;
4692 break;
4693 case glslang::EOpEqual:
4694 case glslang::EOpVectorEqual:
4695 if (isFloat)
4696 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004697 else if (isBool)
4698 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004699 else
4700 binOp = spv::OpIEqual;
4701 break;
4702 case glslang::EOpNotEqual:
4703 case glslang::EOpVectorNotEqual:
4704 if (isFloat)
4705 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004706 else if (isBool)
4707 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004708 else
4709 binOp = spv::OpINotEqual;
4710 break;
4711 default:
4712 break;
4713 }
4714
qining25262b32016-05-06 17:25:16 -04004715 if (binOp != spv::OpNop) {
4716 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004717 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004718 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004719 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004720 }
John Kessenich140f3df2015-06-26 16:58:36 -06004721
4722 return 0;
4723}
4724
John Kessenich04bb8a02015-12-12 12:28:14 -07004725//
4726// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4727// These can be any of:
4728//
4729// matrix * scalar
4730// scalar * matrix
4731// matrix * matrix linear algebraic
4732// matrix * vector
4733// vector * matrix
4734// matrix * matrix componentwise
4735// matrix op matrix op in {+, -, /}
4736// matrix op scalar op in {+, -, /}
4737// scalar op matrix op in {+, -, /}
4738//
John Kessenichead86222018-03-28 18:01:20 -06004739spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4740 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004741{
4742 bool firstClass = true;
4743
4744 // First, handle first-class matrix operations (* and matrix/scalar)
4745 switch (op) {
4746 case spv::OpFDiv:
4747 if (builder.isMatrix(left) && builder.isScalar(right)) {
4748 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004749 spv::Id resultType = builder.getTypeId(right);
4750 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004751 op = spv::OpMatrixTimesScalar;
4752 } else
4753 firstClass = false;
4754 break;
4755 case spv::OpMatrixTimesScalar:
4756 if (builder.isMatrix(right))
4757 std::swap(left, right);
4758 assert(builder.isScalar(right));
4759 break;
4760 case spv::OpVectorTimesMatrix:
4761 assert(builder.isVector(left));
4762 assert(builder.isMatrix(right));
4763 break;
4764 case spv::OpMatrixTimesVector:
4765 assert(builder.isMatrix(left));
4766 assert(builder.isVector(right));
4767 break;
4768 case spv::OpMatrixTimesMatrix:
4769 assert(builder.isMatrix(left));
4770 assert(builder.isMatrix(right));
4771 break;
4772 default:
4773 firstClass = false;
4774 break;
4775 }
4776
qining25262b32016-05-06 17:25:16 -04004777 if (firstClass) {
4778 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004779 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004780 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004781 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004782 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004783
LoopDawg592860c2016-06-09 08:57:35 -06004784 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004785 // The result type of all of them is the same type as the (a) matrix operand.
4786 // The algorithm is to:
4787 // - break the matrix(es) into vectors
4788 // - smear any scalar to a vector
4789 // - do vector operations
4790 // - make a matrix out the vector results
4791 switch (op) {
4792 case spv::OpFAdd:
4793 case spv::OpFSub:
4794 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004795 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004796 case spv::OpFMul:
4797 {
4798 // one time set up...
4799 bool leftMat = builder.isMatrix(left);
4800 bool rightMat = builder.isMatrix(right);
4801 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4802 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4803 spv::Id scalarType = builder.getScalarTypeId(typeId);
4804 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4805 std::vector<spv::Id> results;
4806 spv::Id smearVec = spv::NoResult;
4807 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004808 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004809 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004810 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004811
4812 // do each vector op
4813 for (unsigned int c = 0; c < numCols; ++c) {
4814 std::vector<unsigned int> indexes;
4815 indexes.push_back(c);
4816 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4817 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004818 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004819 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004820 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004821 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004822 }
4823
4824 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004825 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004826 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004827 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004828 }
4829 default:
4830 assert(0);
4831 return spv::NoResult;
4832 }
4833}
4834
John Kessenichead86222018-03-28 18:01:20 -06004835spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4836 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004837{
4838 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004839 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004840 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004841 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4842 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004843
4844 switch (op) {
4845 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004846 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004847 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004848 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004849 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004850 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004851 unaryOp = spv::OpSNegate;
4852 break;
4853
4854 case glslang::EOpLogicalNot:
4855 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004856 unaryOp = spv::OpLogicalNot;
4857 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004858 case glslang::EOpBitwiseNot:
4859 unaryOp = spv::OpNot;
4860 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004861
John Kessenich140f3df2015-06-26 16:58:36 -06004862 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004863 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004864 break;
4865 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004866 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004867 break;
4868 case glslang::EOpTranspose:
4869 unaryOp = spv::OpTranspose;
4870 break;
4871
4872 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004873 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004874 break;
4875 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004876 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004877 break;
4878 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004879 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004880 break;
4881 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004882 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004883 break;
4884 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004885 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004886 break;
4887 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004888 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004889 break;
4890 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004891 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004892 break;
4893 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004894 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004895 break;
4896
4897 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004898 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004899 break;
4900 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004901 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004902 break;
4903 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004904 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004905 break;
4906 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004907 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004908 break;
4909 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004910 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004911 break;
4912 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004913 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004914 break;
4915
4916 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004917 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004918 break;
4919 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004920 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004921 break;
4922
4923 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004924 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004925 break;
4926 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004927 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004928 break;
4929 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004930 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004931 break;
4932 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004933 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004934 break;
4935 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004936 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004937 break;
4938 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004939 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004940 break;
4941
4942 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004943 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004944 break;
4945 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004946 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004947 break;
4948 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004949 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004950 break;
4951 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004952 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004953 break;
4954 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004955 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004956 break;
4957 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004958 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004959 break;
4960
4961 case glslang::EOpIsNan:
4962 unaryOp = spv::OpIsNan;
4963 break;
4964 case glslang::EOpIsInf:
4965 unaryOp = spv::OpIsInf;
4966 break;
LoopDawg592860c2016-06-09 08:57:35 -06004967 case glslang::EOpIsFinite:
4968 unaryOp = spv::OpIsFinite;
4969 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004970
Rex Xucbc426e2015-12-15 16:03:10 +08004971 case glslang::EOpFloatBitsToInt:
4972 case glslang::EOpFloatBitsToUint:
4973 case glslang::EOpIntBitsToFloat:
4974 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004975 case glslang::EOpDoubleBitsToInt64:
4976 case glslang::EOpDoubleBitsToUint64:
4977 case glslang::EOpInt64BitsToDouble:
4978 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004979 case glslang::EOpFloat16BitsToInt16:
4980 case glslang::EOpFloat16BitsToUint16:
4981 case glslang::EOpInt16BitsToFloat16:
4982 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004983 unaryOp = spv::OpBitcast;
4984 break;
4985
John Kessenich140f3df2015-06-26 16:58:36 -06004986 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004987 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004988 break;
4989 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004991 break;
4992 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004993 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004996 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004997 break;
4998 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004999 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005000 break;
5001 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005002 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005003 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005004 case glslang::EOpPackSnorm4x8:
5005 libCall = spv::GLSLstd450PackSnorm4x8;
5006 break;
5007 case glslang::EOpUnpackSnorm4x8:
5008 libCall = spv::GLSLstd450UnpackSnorm4x8;
5009 break;
5010 case glslang::EOpPackUnorm4x8:
5011 libCall = spv::GLSLstd450PackUnorm4x8;
5012 break;
5013 case glslang::EOpUnpackUnorm4x8:
5014 libCall = spv::GLSLstd450UnpackUnorm4x8;
5015 break;
5016 case glslang::EOpPackDouble2x32:
5017 libCall = spv::GLSLstd450PackDouble2x32;
5018 break;
5019 case glslang::EOpUnpackDouble2x32:
5020 libCall = spv::GLSLstd450UnpackDouble2x32;
5021 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005022
Rex Xu8ff43de2016-04-22 16:51:45 +08005023 case glslang::EOpPackInt2x32:
5024 case glslang::EOpUnpackInt2x32:
5025 case glslang::EOpPackUint2x32:
5026 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005027 case glslang::EOpPack16:
5028 case glslang::EOpPack32:
5029 case glslang::EOpPack64:
5030 case glslang::EOpUnpack32:
5031 case glslang::EOpUnpack16:
5032 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005033 case glslang::EOpPackInt2x16:
5034 case glslang::EOpUnpackInt2x16:
5035 case glslang::EOpPackUint2x16:
5036 case glslang::EOpUnpackUint2x16:
5037 case glslang::EOpPackInt4x16:
5038 case glslang::EOpUnpackInt4x16:
5039 case glslang::EOpPackUint4x16:
5040 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005041 case glslang::EOpPackFloat2x16:
5042 case glslang::EOpUnpackFloat2x16:
5043 unaryOp = spv::OpBitcast;
5044 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005045
John Kessenich140f3df2015-06-26 16:58:36 -06005046 case glslang::EOpDPdx:
5047 unaryOp = spv::OpDPdx;
5048 break;
5049 case glslang::EOpDPdy:
5050 unaryOp = spv::OpDPdy;
5051 break;
5052 case glslang::EOpFwidth:
5053 unaryOp = spv::OpFwidth;
5054 break;
5055 case glslang::EOpDPdxFine:
5056 unaryOp = spv::OpDPdxFine;
5057 break;
5058 case glslang::EOpDPdyFine:
5059 unaryOp = spv::OpDPdyFine;
5060 break;
5061 case glslang::EOpFwidthFine:
5062 unaryOp = spv::OpFwidthFine;
5063 break;
5064 case glslang::EOpDPdxCoarse:
5065 unaryOp = spv::OpDPdxCoarse;
5066 break;
5067 case glslang::EOpDPdyCoarse:
5068 unaryOp = spv::OpDPdyCoarse;
5069 break;
5070 case glslang::EOpFwidthCoarse:
5071 unaryOp = spv::OpFwidthCoarse;
5072 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005073 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005074#ifdef AMD_EXTENSIONS
5075 if (typeProxy == glslang::EbtFloat16)
5076 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5077#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005078 libCall = spv::GLSLstd450InterpolateAtCentroid;
5079 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005080 case glslang::EOpAny:
5081 unaryOp = spv::OpAny;
5082 break;
5083 case glslang::EOpAll:
5084 unaryOp = spv::OpAll;
5085 break;
5086
5087 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005088 if (isFloat)
5089 libCall = spv::GLSLstd450FAbs;
5090 else
5091 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005092 break;
5093 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005094 if (isFloat)
5095 libCall = spv::GLSLstd450FSign;
5096 else
5097 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005098 break;
5099
John Kessenichfc51d282015-08-19 13:34:18 -06005100 case glslang::EOpAtomicCounterIncrement:
5101 case glslang::EOpAtomicCounterDecrement:
5102 case glslang::EOpAtomicCounter:
5103 {
5104 // Handle all of the atomics in one place, in createAtomicOperation()
5105 std::vector<spv::Id> operands;
5106 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005107 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005108 }
5109
John Kessenichfc51d282015-08-19 13:34:18 -06005110 case glslang::EOpBitFieldReverse:
5111 unaryOp = spv::OpBitReverse;
5112 break;
5113 case glslang::EOpBitCount:
5114 unaryOp = spv::OpBitCount;
5115 break;
5116 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005117 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005118 break;
5119 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005120 if (isUnsigned)
5121 libCall = spv::GLSLstd450FindUMsb;
5122 else
5123 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005124 break;
5125
Rex Xu574ab042016-04-14 16:53:07 +08005126 case glslang::EOpBallot:
5127 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005128 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005129 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005130 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005131#ifdef AMD_EXTENSIONS
5132 case glslang::EOpMinInvocations:
5133 case glslang::EOpMaxInvocations:
5134 case glslang::EOpAddInvocations:
5135 case glslang::EOpMinInvocationsNonUniform:
5136 case glslang::EOpMaxInvocationsNonUniform:
5137 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005138 case glslang::EOpMinInvocationsInclusiveScan:
5139 case glslang::EOpMaxInvocationsInclusiveScan:
5140 case glslang::EOpAddInvocationsInclusiveScan:
5141 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5142 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5143 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5144 case glslang::EOpMinInvocationsExclusiveScan:
5145 case glslang::EOpMaxInvocationsExclusiveScan:
5146 case glslang::EOpAddInvocationsExclusiveScan:
5147 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5148 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5149 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005150#endif
Rex Xu51596642016-09-21 18:56:12 +08005151 {
5152 std::vector<spv::Id> operands;
5153 operands.push_back(operand);
5154 return createInvocationsOperation(op, typeId, operands, typeProxy);
5155 }
John Kessenich66011cb2018-03-06 16:12:04 -07005156 case glslang::EOpSubgroupAll:
5157 case glslang::EOpSubgroupAny:
5158 case glslang::EOpSubgroupAllEqual:
5159 case glslang::EOpSubgroupBroadcastFirst:
5160 case glslang::EOpSubgroupBallot:
5161 case glslang::EOpSubgroupInverseBallot:
5162 case glslang::EOpSubgroupBallotBitCount:
5163 case glslang::EOpSubgroupBallotInclusiveBitCount:
5164 case glslang::EOpSubgroupBallotExclusiveBitCount:
5165 case glslang::EOpSubgroupBallotFindLSB:
5166 case glslang::EOpSubgroupBallotFindMSB:
5167 case glslang::EOpSubgroupAdd:
5168 case glslang::EOpSubgroupMul:
5169 case glslang::EOpSubgroupMin:
5170 case glslang::EOpSubgroupMax:
5171 case glslang::EOpSubgroupAnd:
5172 case glslang::EOpSubgroupOr:
5173 case glslang::EOpSubgroupXor:
5174 case glslang::EOpSubgroupInclusiveAdd:
5175 case glslang::EOpSubgroupInclusiveMul:
5176 case glslang::EOpSubgroupInclusiveMin:
5177 case glslang::EOpSubgroupInclusiveMax:
5178 case glslang::EOpSubgroupInclusiveAnd:
5179 case glslang::EOpSubgroupInclusiveOr:
5180 case glslang::EOpSubgroupInclusiveXor:
5181 case glslang::EOpSubgroupExclusiveAdd:
5182 case glslang::EOpSubgroupExclusiveMul:
5183 case glslang::EOpSubgroupExclusiveMin:
5184 case glslang::EOpSubgroupExclusiveMax:
5185 case glslang::EOpSubgroupExclusiveAnd:
5186 case glslang::EOpSubgroupExclusiveOr:
5187 case glslang::EOpSubgroupExclusiveXor:
5188 case glslang::EOpSubgroupQuadSwapHorizontal:
5189 case glslang::EOpSubgroupQuadSwapVertical:
5190 case glslang::EOpSubgroupQuadSwapDiagonal: {
5191 std::vector<spv::Id> operands;
5192 operands.push_back(operand);
5193 return createSubgroupOperation(op, typeId, operands, typeProxy);
5194 }
Rex Xu9d93a232016-05-05 12:30:44 +08005195#ifdef AMD_EXTENSIONS
5196 case glslang::EOpMbcnt:
5197 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5198 libCall = spv::MbcntAMD;
5199 break;
5200
5201 case glslang::EOpCubeFaceIndex:
5202 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5203 libCall = spv::CubeFaceIndexAMD;
5204 break;
5205
5206 case glslang::EOpCubeFaceCoord:
5207 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5208 libCall = spv::CubeFaceCoordAMD;
5209 break;
5210#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005211#ifdef NV_EXTENSIONS
5212 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005213 unaryOp = spv::OpGroupNonUniformPartitionNV;
5214 break;
5215#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005216 default:
5217 return 0;
5218 }
5219
5220 spv::Id id;
5221 if (libCall >= 0) {
5222 std::vector<spv::Id> args;
5223 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005224 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005225 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005226 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005227 }
John Kessenich140f3df2015-06-26 16:58:36 -06005228
John Kessenichead86222018-03-28 18:01:20 -06005229 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005230 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005231 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005232}
5233
John Kessenich7a53f762016-01-20 11:19:27 -07005234// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005235spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5236 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005237{
5238 // Handle unary operations vector by vector.
5239 // The result type is the same type as the original type.
5240 // The algorithm is to:
5241 // - break the matrix into vectors
5242 // - apply the operation to each vector
5243 // - make a matrix out the vector results
5244
5245 // get the types sorted out
5246 int numCols = builder.getNumColumns(operand);
5247 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005248 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5249 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005250 std::vector<spv::Id> results;
5251
5252 // do each vector op
5253 for (int c = 0; c < numCols; ++c) {
5254 std::vector<unsigned int> indexes;
5255 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005256 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5257 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005258 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005259 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005260 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005261 }
5262
5263 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005264 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005265 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005266 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005267}
5268
John Kessenichad7645f2018-06-04 19:11:25 -06005269// For converting integers where both the bitwidth and the signedness could
5270// change, but only do the width change here. The caller is still responsible
5271// for the signedness conversion.
5272spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005273{
John Kessenichad7645f2018-06-04 19:11:25 -06005274 // Get the result type width, based on the type to convert to.
5275 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005276 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005277 case glslang::EOpConvInt16ToUint8:
5278 case glslang::EOpConvIntToUint8:
5279 case glslang::EOpConvInt64ToUint8:
5280 case glslang::EOpConvUint16ToInt8:
5281 case glslang::EOpConvUintToInt8:
5282 case glslang::EOpConvUint64ToInt8:
5283 width = 8;
5284 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005285 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005286 case glslang::EOpConvIntToUint16:
5287 case glslang::EOpConvInt64ToUint16:
5288 case glslang::EOpConvUint8ToInt16:
5289 case glslang::EOpConvUintToInt16:
5290 case glslang::EOpConvUint64ToInt16:
5291 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005292 break;
5293 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005294 case glslang::EOpConvInt16ToUint:
5295 case glslang::EOpConvInt64ToUint:
5296 case glslang::EOpConvUint8ToInt:
5297 case glslang::EOpConvUint16ToInt:
5298 case glslang::EOpConvUint64ToInt:
5299 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005300 break;
5301 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005302 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005303 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005304 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005305 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005306 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005307 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005308 break;
5309
5310 default:
5311 assert(false && "Default missing");
5312 break;
5313 }
5314
John Kessenichad7645f2018-06-04 19:11:25 -06005315 // Get the conversion operation and result type,
5316 // based on the target width, but the source type.
5317 spv::Id type = spv::NoType;
5318 spv::Op convOp = spv::OpNop;
5319 switch(op) {
5320 case glslang::EOpConvInt8ToUint16:
5321 case glslang::EOpConvInt8ToUint:
5322 case glslang::EOpConvInt8ToUint64:
5323 case glslang::EOpConvInt16ToUint8:
5324 case glslang::EOpConvInt16ToUint:
5325 case glslang::EOpConvInt16ToUint64:
5326 case glslang::EOpConvIntToUint8:
5327 case glslang::EOpConvIntToUint16:
5328 case glslang::EOpConvIntToUint64:
5329 case glslang::EOpConvInt64ToUint8:
5330 case glslang::EOpConvInt64ToUint16:
5331 case glslang::EOpConvInt64ToUint:
5332 convOp = spv::OpSConvert;
5333 type = builder.makeIntType(width);
5334 break;
5335 default:
5336 convOp = spv::OpUConvert;
5337 type = builder.makeUintType(width);
5338 break;
5339 }
5340
John Kessenich66011cb2018-03-06 16:12:04 -07005341 if (vectorSize > 0)
5342 type = builder.makeVectorType(type, vectorSize);
5343
John Kessenichad7645f2018-06-04 19:11:25 -06005344 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005345}
5346
John Kessenichead86222018-03-28 18:01:20 -06005347spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5348 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005349{
5350 spv::Op convOp = spv::OpNop;
5351 spv::Id zero = 0;
5352 spv::Id one = 0;
5353
5354 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5355
5356 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005357 case glslang::EOpConvInt8ToBool:
5358 case glslang::EOpConvUint8ToBool:
5359 zero = builder.makeUint8Constant(0);
5360 zero = makeSmearedConstant(zero, vectorSize);
5361 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005362 case glslang::EOpConvInt16ToBool:
5363 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005364 zero = builder.makeUint16Constant(0);
5365 zero = makeSmearedConstant(zero, vectorSize);
5366 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5367 case glslang::EOpConvIntToBool:
5368 case glslang::EOpConvUintToBool:
5369 zero = builder.makeUintConstant(0);
5370 zero = makeSmearedConstant(zero, vectorSize);
5371 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5372 case glslang::EOpConvInt64ToBool:
5373 case glslang::EOpConvUint64ToBool:
5374 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005375 zero = makeSmearedConstant(zero, vectorSize);
5376 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5377
5378 case glslang::EOpConvFloatToBool:
5379 zero = builder.makeFloatConstant(0.0F);
5380 zero = makeSmearedConstant(zero, vectorSize);
5381 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5382
5383 case glslang::EOpConvDoubleToBool:
5384 zero = builder.makeDoubleConstant(0.0);
5385 zero = makeSmearedConstant(zero, vectorSize);
5386 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5387
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005388 case glslang::EOpConvFloat16ToBool:
5389 zero = builder.makeFloat16Constant(0.0F);
5390 zero = makeSmearedConstant(zero, vectorSize);
5391 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005392
John Kessenich140f3df2015-06-26 16:58:36 -06005393 case glslang::EOpConvBoolToFloat:
5394 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005395 zero = builder.makeFloatConstant(0.0F);
5396 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005397 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005398
John Kessenich140f3df2015-06-26 16:58:36 -06005399 case glslang::EOpConvBoolToDouble:
5400 convOp = spv::OpSelect;
5401 zero = builder.makeDoubleConstant(0.0);
5402 one = builder.makeDoubleConstant(1.0);
5403 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005404
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005405 case glslang::EOpConvBoolToFloat16:
5406 convOp = spv::OpSelect;
5407 zero = builder.makeFloat16Constant(0.0F);
5408 one = builder.makeFloat16Constant(1.0F);
5409 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005410
5411 case glslang::EOpConvBoolToInt8:
5412 zero = builder.makeInt8Constant(0);
5413 one = builder.makeInt8Constant(1);
5414 convOp = spv::OpSelect;
5415 break;
5416
5417 case glslang::EOpConvBoolToUint8:
5418 zero = builder.makeUint8Constant(0);
5419 one = builder.makeUint8Constant(1);
5420 convOp = spv::OpSelect;
5421 break;
5422
5423 case glslang::EOpConvBoolToInt16:
5424 zero = builder.makeInt16Constant(0);
5425 one = builder.makeInt16Constant(1);
5426 convOp = spv::OpSelect;
5427 break;
5428
5429 case glslang::EOpConvBoolToUint16:
5430 zero = builder.makeUint16Constant(0);
5431 one = builder.makeUint16Constant(1);
5432 convOp = spv::OpSelect;
5433 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005434
John Kessenich140f3df2015-06-26 16:58:36 -06005435 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005436 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005437 if (op == glslang::EOpConvBoolToInt64)
5438 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005439 else
5440 zero = builder.makeIntConstant(0);
5441
5442 if (op == glslang::EOpConvBoolToInt64)
5443 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005444 else
5445 one = builder.makeIntConstant(1);
5446
John Kessenich140f3df2015-06-26 16:58:36 -06005447 convOp = spv::OpSelect;
5448 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005449
John Kessenich140f3df2015-06-26 16:58:36 -06005450 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005451 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005452 if (op == glslang::EOpConvBoolToUint64)
5453 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005454 else
5455 zero = builder.makeUintConstant(0);
5456
5457 if (op == glslang::EOpConvBoolToUint64)
5458 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005459 else
5460 one = builder.makeUintConstant(1);
5461
John Kessenich140f3df2015-06-26 16:58:36 -06005462 convOp = spv::OpSelect;
5463 break;
5464
John Kessenich66011cb2018-03-06 16:12:04 -07005465 case glslang::EOpConvInt8ToFloat16:
5466 case glslang::EOpConvInt8ToFloat:
5467 case glslang::EOpConvInt8ToDouble:
5468 case glslang::EOpConvInt16ToFloat16:
5469 case glslang::EOpConvInt16ToFloat:
5470 case glslang::EOpConvInt16ToDouble:
5471 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005472 case glslang::EOpConvIntToFloat:
5473 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005474 case glslang::EOpConvInt64ToFloat:
5475 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005476 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005477 convOp = spv::OpConvertSToF;
5478 break;
5479
John Kessenich66011cb2018-03-06 16:12:04 -07005480 case glslang::EOpConvUint8ToFloat16:
5481 case glslang::EOpConvUint8ToFloat:
5482 case glslang::EOpConvUint8ToDouble:
5483 case glslang::EOpConvUint16ToFloat16:
5484 case glslang::EOpConvUint16ToFloat:
5485 case glslang::EOpConvUint16ToDouble:
5486 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005487 case glslang::EOpConvUintToFloat:
5488 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005489 case glslang::EOpConvUint64ToFloat:
5490 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005491 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005492 convOp = spv::OpConvertUToF;
5493 break;
5494
5495 case glslang::EOpConvDoubleToFloat:
5496 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005497 case glslang::EOpConvDoubleToFloat16:
5498 case glslang::EOpConvFloat16ToDouble:
5499 case glslang::EOpConvFloatToFloat16:
5500 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005501 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005502 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005503 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005504 break;
5505
John Kessenich66011cb2018-03-06 16:12:04 -07005506 case glslang::EOpConvFloat16ToInt8:
5507 case glslang::EOpConvFloatToInt8:
5508 case glslang::EOpConvDoubleToInt8:
5509 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005510 case glslang::EOpConvFloatToInt16:
5511 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005512 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005513 case glslang::EOpConvFloatToInt:
5514 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005515 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005516 case glslang::EOpConvFloatToInt64:
5517 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005518 convOp = spv::OpConvertFToS;
5519 break;
5520
John Kessenich66011cb2018-03-06 16:12:04 -07005521 case glslang::EOpConvUint8ToInt8:
5522 case glslang::EOpConvInt8ToUint8:
5523 case glslang::EOpConvUint16ToInt16:
5524 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005525 case glslang::EOpConvUintToInt:
5526 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005527 case glslang::EOpConvUint64ToInt64:
5528 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005529 if (builder.isInSpecConstCodeGenMode()) {
5530 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005531 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5532 zero = builder.makeUint8Constant(0);
5533 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005534 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005535 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5536 zero = builder.makeUint64Constant(0);
5537 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005538 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005539 }
qining189b2032016-04-12 23:16:20 -04005540 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005541 // Use OpIAdd, instead of OpBitcast to do the conversion when
5542 // generating for OpSpecConstantOp instruction.
5543 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5544 }
5545 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005546 convOp = spv::OpBitcast;
5547 break;
5548
John Kessenich66011cb2018-03-06 16:12:04 -07005549 case glslang::EOpConvFloat16ToUint8:
5550 case glslang::EOpConvFloatToUint8:
5551 case glslang::EOpConvDoubleToUint8:
5552 case glslang::EOpConvFloat16ToUint16:
5553 case glslang::EOpConvFloatToUint16:
5554 case glslang::EOpConvDoubleToUint16:
5555 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005556 case glslang::EOpConvFloatToUint:
5557 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005558 case glslang::EOpConvFloatToUint64:
5559 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005560 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005561 convOp = spv::OpConvertFToU;
5562 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005563
John Kessenich66011cb2018-03-06 16:12:04 -07005564 case glslang::EOpConvInt8ToInt16:
5565 case glslang::EOpConvInt8ToInt:
5566 case glslang::EOpConvInt8ToInt64:
5567 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005568 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005569 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005570 case glslang::EOpConvIntToInt8:
5571 case glslang::EOpConvIntToInt16:
5572 case glslang::EOpConvIntToInt64:
5573 case glslang::EOpConvInt64ToInt8:
5574 case glslang::EOpConvInt64ToInt16:
5575 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005576 convOp = spv::OpSConvert;
5577 break;
5578
John Kessenich66011cb2018-03-06 16:12:04 -07005579 case glslang::EOpConvUint8ToUint16:
5580 case glslang::EOpConvUint8ToUint:
5581 case glslang::EOpConvUint8ToUint64:
5582 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005583 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005584 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005585 case glslang::EOpConvUintToUint8:
5586 case glslang::EOpConvUintToUint16:
5587 case glslang::EOpConvUintToUint64:
5588 case glslang::EOpConvUint64ToUint8:
5589 case glslang::EOpConvUint64ToUint16:
5590 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005591 convOp = spv::OpUConvert;
5592 break;
5593
John Kessenich66011cb2018-03-06 16:12:04 -07005594 case glslang::EOpConvInt8ToUint16:
5595 case glslang::EOpConvInt8ToUint:
5596 case glslang::EOpConvInt8ToUint64:
5597 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005598 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005599 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005600 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005601 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005602 case glslang::EOpConvIntToUint64:
5603 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005604 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005605 case glslang::EOpConvInt64ToUint:
5606 case glslang::EOpConvUint8ToInt16:
5607 case glslang::EOpConvUint8ToInt:
5608 case glslang::EOpConvUint8ToInt64:
5609 case glslang::EOpConvUint16ToInt8:
5610 case glslang::EOpConvUint16ToInt:
5611 case glslang::EOpConvUint16ToInt64:
5612 case glslang::EOpConvUintToInt8:
5613 case glslang::EOpConvUintToInt16:
5614 case glslang::EOpConvUintToInt64:
5615 case glslang::EOpConvUint64ToInt8:
5616 case glslang::EOpConvUint64ToInt16:
5617 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005618 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005619 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005620
5621 if (builder.isInSpecConstCodeGenMode()) {
5622 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005623 switch(op) {
5624 case glslang::EOpConvInt16ToUint8:
5625 case glslang::EOpConvIntToUint8:
5626 case glslang::EOpConvInt64ToUint8:
5627 case glslang::EOpConvUint16ToInt8:
5628 case glslang::EOpConvUintToInt8:
5629 case glslang::EOpConvUint64ToInt8:
5630 zero = builder.makeUint8Constant(0);
5631 break;
5632 case glslang::EOpConvInt8ToUint16:
5633 case glslang::EOpConvIntToUint16:
5634 case glslang::EOpConvInt64ToUint16:
5635 case glslang::EOpConvUint8ToInt16:
5636 case glslang::EOpConvUintToInt16:
5637 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005638 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005639 break;
5640 case glslang::EOpConvInt8ToUint:
5641 case glslang::EOpConvInt16ToUint:
5642 case glslang::EOpConvInt64ToUint:
5643 case glslang::EOpConvUint8ToInt:
5644 case glslang::EOpConvUint16ToInt:
5645 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005646 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005647 break;
5648 case glslang::EOpConvInt8ToUint64:
5649 case glslang::EOpConvInt16ToUint64:
5650 case glslang::EOpConvIntToUint64:
5651 case glslang::EOpConvUint8ToInt64:
5652 case glslang::EOpConvUint16ToInt64:
5653 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005654 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005655 break;
5656 default:
5657 assert(false && "Default missing");
5658 break;
5659 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005660 zero = makeSmearedConstant(zero, vectorSize);
5661 // Use OpIAdd, instead of OpBitcast to do the conversion when
5662 // generating for OpSpecConstantOp instruction.
5663 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5664 }
5665 // For normal run-time conversion instruction, use OpBitcast.
5666 convOp = spv::OpBitcast;
5667 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005668 default:
5669 break;
5670 }
5671
5672 spv::Id result = 0;
5673 if (convOp == spv::OpNop)
5674 return result;
5675
5676 if (convOp == spv::OpSelect) {
5677 zero = makeSmearedConstant(zero, vectorSize);
5678 one = makeSmearedConstant(one, vectorSize);
5679 result = builder.createTriOp(convOp, destType, operand, one, zero);
5680 } else
5681 result = builder.createUnaryOp(convOp, destType, operand);
5682
John Kessenichead86222018-03-28 18:01:20 -06005683 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005684 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005685 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005686}
5687
5688spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5689{
5690 if (vectorSize == 0)
5691 return constant;
5692
5693 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5694 std::vector<spv::Id> components;
5695 for (int c = 0; c < vectorSize; ++c)
5696 components.push_back(constant);
5697 return builder.makeCompositeConstant(vectorTypeId, components);
5698}
5699
John Kessenich426394d2015-07-23 10:22:48 -06005700// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005701spv::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 -06005702{
5703 spv::Op opCode = spv::OpNop;
5704
5705 switch (op) {
5706 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005707 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005708 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005709 opCode = spv::OpAtomicIAdd;
5710 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005711 case glslang::EOpAtomicCounterSubtract:
5712 opCode = spv::OpAtomicISub;
5713 break;
John Kessenich426394d2015-07-23 10:22:48 -06005714 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005715 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005716 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005717 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005718 break;
5719 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005720 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005721 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005722 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005723 break;
5724 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005725 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005726 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005727 opCode = spv::OpAtomicAnd;
5728 break;
5729 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005730 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005731 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005732 opCode = spv::OpAtomicOr;
5733 break;
5734 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005735 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005736 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005737 opCode = spv::OpAtomicXor;
5738 break;
5739 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005740 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005741 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005742 opCode = spv::OpAtomicExchange;
5743 break;
5744 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005745 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005746 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005747 opCode = spv::OpAtomicCompareExchange;
5748 break;
5749 case glslang::EOpAtomicCounterIncrement:
5750 opCode = spv::OpAtomicIIncrement;
5751 break;
5752 case glslang::EOpAtomicCounterDecrement:
5753 opCode = spv::OpAtomicIDecrement;
5754 break;
5755 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005756 case glslang::EOpImageAtomicLoad:
5757 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005758 opCode = spv::OpAtomicLoad;
5759 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005760 case glslang::EOpAtomicStore:
5761 case glslang::EOpImageAtomicStore:
5762 opCode = spv::OpAtomicStore;
5763 break;
John Kessenich426394d2015-07-23 10:22:48 -06005764 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005765 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005766 break;
5767 }
5768
Rex Xue8fe8b02017-09-26 15:42:56 +08005769 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5770 builder.addCapability(spv::CapabilityInt64Atomics);
5771
John Kessenich426394d2015-07-23 10:22:48 -06005772 // Sort out the operands
5773 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005774 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005775 // - compare-exchange swaps the value and comparator
5776 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005777 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005778 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5779 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5780 spv::Id scopeId;
5781 if (glslangIntermediate->usingVulkanMemoryModel()) {
5782 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5783 } else {
5784 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5785 }
5786 // semantics default to relaxed
5787 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5788 spv::Id semanticsId2 = semanticsId;
5789
5790 pointerId = operands[0];
5791 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5792 // no additional operands
5793 } else if (opCode == spv::OpAtomicCompareExchange) {
5794 compareId = operands[1];
5795 valueId = operands[2];
5796 if (operands.size() > 3) {
5797 scopeId = operands[3];
5798 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5799 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5800 }
5801 } else if (opCode == spv::OpAtomicLoad) {
5802 if (operands.size() > 1) {
5803 scopeId = operands[1];
5804 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5805 }
5806 } else {
5807 // atomic store or RMW
5808 valueId = operands[1];
5809 if (operands.size() > 2) {
5810 scopeId = operands[2];
5811 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5812 }
Rex Xu04db3f52015-09-16 11:44:02 +08005813 }
John Kessenich426394d2015-07-23 10:22:48 -06005814
Jeff Bolz36831c92018-09-05 10:11:41 -05005815 // Check for capabilities
5816 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5817 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5818 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5819 }
John Kessenich426394d2015-07-23 10:22:48 -06005820
Jeff Bolz36831c92018-09-05 10:11:41 -05005821 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5822 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5823 }
John Kessenich48d6e792017-10-06 21:21:48 -06005824
Jeff Bolz36831c92018-09-05 10:11:41 -05005825 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5826 spvAtomicOperands.push_back(pointerId);
5827 spvAtomicOperands.push_back(scopeId);
5828 spvAtomicOperands.push_back(semanticsId);
5829 if (opCode == spv::OpAtomicCompareExchange) {
5830 spvAtomicOperands.push_back(semanticsId2);
5831 spvAtomicOperands.push_back(valueId);
5832 spvAtomicOperands.push_back(compareId);
5833 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5834 spvAtomicOperands.push_back(valueId);
5835 }
John Kessenich48d6e792017-10-06 21:21:48 -06005836
Jeff Bolz36831c92018-09-05 10:11:41 -05005837 if (opCode == spv::OpAtomicStore) {
5838 builder.createNoResultOp(opCode, spvAtomicOperands);
5839 return 0;
5840 } else {
5841 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5842
5843 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5844 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5845 if (op == glslang::EOpAtomicCounterDecrement)
5846 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5847
5848 return resultId;
5849 }
John Kessenich426394d2015-07-23 10:22:48 -06005850}
5851
John Kessenich91cef522016-05-05 16:45:40 -06005852// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005853spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005854{
Corentin Walleze7061422018-08-08 15:20:15 +02005855#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005856 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5857 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005858#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005859
Rex Xu51596642016-09-21 18:56:12 +08005860 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005861 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005862 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5863
chaocf200da82016-12-20 12:44:35 -08005864 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5865 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005866 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5867 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005868 } else if (op == glslang::EOpAnyInvocation ||
5869 op == glslang::EOpAllInvocations ||
5870 op == glslang::EOpAllInvocationsEqual) {
5871 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5872 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005873 } else {
5874 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005875#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005876 if (op == glslang::EOpMinInvocationsNonUniform ||
5877 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005878 op == glslang::EOpAddInvocationsNonUniform ||
5879 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5880 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5881 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5882 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5883 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5884 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005885 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005886#endif
Rex Xu51596642016-09-21 18:56:12 +08005887
Rex Xu9d93a232016-05-05 12:30:44 +08005888#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005889 switch (op) {
5890 case glslang::EOpMinInvocations:
5891 case glslang::EOpMaxInvocations:
5892 case glslang::EOpAddInvocations:
5893 case glslang::EOpMinInvocationsNonUniform:
5894 case glslang::EOpMaxInvocationsNonUniform:
5895 case glslang::EOpAddInvocationsNonUniform:
5896 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005897 break;
5898 case glslang::EOpMinInvocationsInclusiveScan:
5899 case glslang::EOpMaxInvocationsInclusiveScan:
5900 case glslang::EOpAddInvocationsInclusiveScan:
5901 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5902 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5903 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5904 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005905 break;
5906 case glslang::EOpMinInvocationsExclusiveScan:
5907 case glslang::EOpMaxInvocationsExclusiveScan:
5908 case glslang::EOpAddInvocationsExclusiveScan:
5909 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5910 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5911 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5912 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005913 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005914 default:
5915 break;
Rex Xu430ef402016-10-14 17:22:23 +08005916 }
John Kessenich149afc32018-08-14 13:31:43 -06005917 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5918 spvGroupOperands.push_back(scope);
5919 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06005920 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005921 spvGroupOperands.push_back(groupOp);
5922 }
Rex Xu9d93a232016-05-05 12:30:44 +08005923#endif
Rex Xu51596642016-09-21 18:56:12 +08005924 }
5925
John Kessenich149afc32018-08-14 13:31:43 -06005926 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5927 spv::IdImmediate op = { true, *opIt };
5928 spvGroupOperands.push_back(op);
5929 }
John Kessenich91cef522016-05-05 16:45:40 -06005930
5931 switch (op) {
5932 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005933 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005934 break;
John Kessenich91cef522016-05-05 16:45:40 -06005935 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005936 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005937 break;
John Kessenich91cef522016-05-05 16:45:40 -06005938 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005939 opCode = spv::OpSubgroupAllEqualKHR;
5940 break;
Rex Xu51596642016-09-21 18:56:12 +08005941 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005942 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005943 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005944 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005945 break;
5946 case glslang::EOpReadFirstInvocation:
5947 opCode = spv::OpSubgroupFirstInvocationKHR;
5948 break;
5949 case glslang::EOpBallot:
5950 {
5951 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5952 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5953 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5954 //
5955 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5956 //
5957 spv::Id uintType = builder.makeUintType(32);
5958 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5959 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5960
5961 std::vector<spv::Id> components;
5962 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5963 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5964
5965 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5966 return builder.createUnaryOp(spv::OpBitcast, typeId,
5967 builder.createCompositeConstruct(uvec2Type, components));
5968 }
5969
Rex Xu9d93a232016-05-05 12:30:44 +08005970#ifdef AMD_EXTENSIONS
5971 case glslang::EOpMinInvocations:
5972 case glslang::EOpMaxInvocations:
5973 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005974 case glslang::EOpMinInvocationsInclusiveScan:
5975 case glslang::EOpMaxInvocationsInclusiveScan:
5976 case glslang::EOpAddInvocationsInclusiveScan:
5977 case glslang::EOpMinInvocationsExclusiveScan:
5978 case glslang::EOpMaxInvocationsExclusiveScan:
5979 case glslang::EOpAddInvocationsExclusiveScan:
5980 if (op == glslang::EOpMinInvocations ||
5981 op == glslang::EOpMinInvocationsInclusiveScan ||
5982 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005983 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005984 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005985 else {
5986 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005987 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005988 else
Rex Xu51596642016-09-21 18:56:12 +08005989 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005990 }
Rex Xu430ef402016-10-14 17:22:23 +08005991 } else if (op == glslang::EOpMaxInvocations ||
5992 op == glslang::EOpMaxInvocationsInclusiveScan ||
5993 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005994 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005995 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005996 else {
5997 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005998 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005999 else
Rex Xu51596642016-09-21 18:56:12 +08006000 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006001 }
6002 } else {
6003 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006004 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006005 else
Rex Xu51596642016-09-21 18:56:12 +08006006 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006007 }
6008
Rex Xu2bbbe062016-08-23 15:41:05 +08006009 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006010 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006011
6012 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006013 case glslang::EOpMinInvocationsNonUniform:
6014 case glslang::EOpMaxInvocationsNonUniform:
6015 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006016 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6017 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6018 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6019 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6020 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6021 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6022 if (op == glslang::EOpMinInvocationsNonUniform ||
6023 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6024 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006025 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006026 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006027 else {
6028 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006029 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006030 else
Rex Xu51596642016-09-21 18:56:12 +08006031 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006032 }
6033 }
Rex Xu430ef402016-10-14 17:22:23 +08006034 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6035 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6036 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006037 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006038 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006039 else {
6040 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006041 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006042 else
Rex Xu51596642016-09-21 18:56:12 +08006043 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006044 }
6045 }
6046 else {
6047 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006048 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006049 else
Rex Xu51596642016-09-21 18:56:12 +08006050 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006051 }
6052
Rex Xu2bbbe062016-08-23 15:41:05 +08006053 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006054 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006055
6056 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006057#endif
John Kessenich91cef522016-05-05 16:45:40 -06006058 default:
6059 logger->missingFunctionality("invocation operation");
6060 return spv::NoResult;
6061 }
Rex Xu51596642016-09-21 18:56:12 +08006062
6063 assert(opCode != spv::OpNop);
6064 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006065}
6066
Rex Xu2bbbe062016-08-23 15:41:05 +08006067// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006068spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6069 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006070{
Rex Xub7072052016-09-26 15:53:40 +08006071#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006072 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6073 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006074 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006075 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006076 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6077 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6078 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006079#else
6080 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6081 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006082 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6083 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006084#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006085
6086 // Handle group invocation operations scalar by scalar.
6087 // The result type is the same type as the original type.
6088 // The algorithm is to:
6089 // - break the vector into scalars
6090 // - apply the operation to each scalar
6091 // - make a vector out the scalar results
6092
6093 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006094 int numComponents = builder.getNumComponents(operands[0]);
6095 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006096 std::vector<spv::Id> results;
6097
6098 // do each scalar op
6099 for (int comp = 0; comp < numComponents; ++comp) {
6100 std::vector<unsigned int> indexes;
6101 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006102 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6103 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006104 if (op == spv::OpSubgroupReadInvocationKHR) {
6105 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006106 spv::IdImmediate operand = { true, operands[1] };
6107 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006108 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006109 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6110 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006111 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006112 spv::IdImmediate operand = { true, operands[1] };
6113 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006114 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006115 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6116 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006117 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006118 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006119 spvGroupOperands.push_back(scalar);
6120 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006121
Rex Xub7072052016-09-26 15:53:40 +08006122 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006123 }
6124
6125 // put the pieces together
6126 return builder.createCompositeConstruct(typeId, results);
6127}
Rex Xu2bbbe062016-08-23 15:41:05 +08006128
John Kessenich66011cb2018-03-06 16:12:04 -07006129// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006130spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6131 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006132{
6133 // Add the required capabilities.
6134 switch (op) {
6135 case glslang::EOpSubgroupElect:
6136 builder.addCapability(spv::CapabilityGroupNonUniform);
6137 break;
6138 case glslang::EOpSubgroupAll:
6139 case glslang::EOpSubgroupAny:
6140 case glslang::EOpSubgroupAllEqual:
6141 builder.addCapability(spv::CapabilityGroupNonUniform);
6142 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6143 break;
6144 case glslang::EOpSubgroupBroadcast:
6145 case glslang::EOpSubgroupBroadcastFirst:
6146 case glslang::EOpSubgroupBallot:
6147 case glslang::EOpSubgroupInverseBallot:
6148 case glslang::EOpSubgroupBallotBitExtract:
6149 case glslang::EOpSubgroupBallotBitCount:
6150 case glslang::EOpSubgroupBallotInclusiveBitCount:
6151 case glslang::EOpSubgroupBallotExclusiveBitCount:
6152 case glslang::EOpSubgroupBallotFindLSB:
6153 case glslang::EOpSubgroupBallotFindMSB:
6154 builder.addCapability(spv::CapabilityGroupNonUniform);
6155 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6156 break;
6157 case glslang::EOpSubgroupShuffle:
6158 case glslang::EOpSubgroupShuffleXor:
6159 builder.addCapability(spv::CapabilityGroupNonUniform);
6160 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6161 break;
6162 case glslang::EOpSubgroupShuffleUp:
6163 case glslang::EOpSubgroupShuffleDown:
6164 builder.addCapability(spv::CapabilityGroupNonUniform);
6165 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6166 break;
6167 case glslang::EOpSubgroupAdd:
6168 case glslang::EOpSubgroupMul:
6169 case glslang::EOpSubgroupMin:
6170 case glslang::EOpSubgroupMax:
6171 case glslang::EOpSubgroupAnd:
6172 case glslang::EOpSubgroupOr:
6173 case glslang::EOpSubgroupXor:
6174 case glslang::EOpSubgroupInclusiveAdd:
6175 case glslang::EOpSubgroupInclusiveMul:
6176 case glslang::EOpSubgroupInclusiveMin:
6177 case glslang::EOpSubgroupInclusiveMax:
6178 case glslang::EOpSubgroupInclusiveAnd:
6179 case glslang::EOpSubgroupInclusiveOr:
6180 case glslang::EOpSubgroupInclusiveXor:
6181 case glslang::EOpSubgroupExclusiveAdd:
6182 case glslang::EOpSubgroupExclusiveMul:
6183 case glslang::EOpSubgroupExclusiveMin:
6184 case glslang::EOpSubgroupExclusiveMax:
6185 case glslang::EOpSubgroupExclusiveAnd:
6186 case glslang::EOpSubgroupExclusiveOr:
6187 case glslang::EOpSubgroupExclusiveXor:
6188 builder.addCapability(spv::CapabilityGroupNonUniform);
6189 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6190 break;
6191 case glslang::EOpSubgroupClusteredAdd:
6192 case glslang::EOpSubgroupClusteredMul:
6193 case glslang::EOpSubgroupClusteredMin:
6194 case glslang::EOpSubgroupClusteredMax:
6195 case glslang::EOpSubgroupClusteredAnd:
6196 case glslang::EOpSubgroupClusteredOr:
6197 case glslang::EOpSubgroupClusteredXor:
6198 builder.addCapability(spv::CapabilityGroupNonUniform);
6199 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6200 break;
6201 case glslang::EOpSubgroupQuadBroadcast:
6202 case glslang::EOpSubgroupQuadSwapHorizontal:
6203 case glslang::EOpSubgroupQuadSwapVertical:
6204 case glslang::EOpSubgroupQuadSwapDiagonal:
6205 builder.addCapability(spv::CapabilityGroupNonUniform);
6206 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6207 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006208#ifdef NV_EXTENSIONS
6209 case glslang::EOpSubgroupPartitionedAdd:
6210 case glslang::EOpSubgroupPartitionedMul:
6211 case glslang::EOpSubgroupPartitionedMin:
6212 case glslang::EOpSubgroupPartitionedMax:
6213 case glslang::EOpSubgroupPartitionedAnd:
6214 case glslang::EOpSubgroupPartitionedOr:
6215 case glslang::EOpSubgroupPartitionedXor:
6216 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6217 case glslang::EOpSubgroupPartitionedInclusiveMul:
6218 case glslang::EOpSubgroupPartitionedInclusiveMin:
6219 case glslang::EOpSubgroupPartitionedInclusiveMax:
6220 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6221 case glslang::EOpSubgroupPartitionedInclusiveOr:
6222 case glslang::EOpSubgroupPartitionedInclusiveXor:
6223 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6224 case glslang::EOpSubgroupPartitionedExclusiveMul:
6225 case glslang::EOpSubgroupPartitionedExclusiveMin:
6226 case glslang::EOpSubgroupPartitionedExclusiveMax:
6227 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6228 case glslang::EOpSubgroupPartitionedExclusiveOr:
6229 case glslang::EOpSubgroupPartitionedExclusiveXor:
6230 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6231 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6232 break;
6233#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006234 default: assert(0 && "Unhandled subgroup operation!");
6235 }
6236
6237 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6238 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6239 const bool isBool = typeProxy == glslang::EbtBool;
6240
6241 spv::Op opCode = spv::OpNop;
6242
6243 // Figure out which opcode to use.
6244 switch (op) {
6245 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6246 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6247 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6248 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6249 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6250 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6251 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6252 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6253 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6254 case glslang::EOpSubgroupBallotBitCount:
6255 case glslang::EOpSubgroupBallotInclusiveBitCount:
6256 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6257 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6258 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6259 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6260 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6261 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6262 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6263 case glslang::EOpSubgroupAdd:
6264 case glslang::EOpSubgroupInclusiveAdd:
6265 case glslang::EOpSubgroupExclusiveAdd:
6266 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006267#ifdef NV_EXTENSIONS
6268 case glslang::EOpSubgroupPartitionedAdd:
6269 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6270 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6271#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006272 if (isFloat) {
6273 opCode = spv::OpGroupNonUniformFAdd;
6274 } else {
6275 opCode = spv::OpGroupNonUniformIAdd;
6276 }
6277 break;
6278 case glslang::EOpSubgroupMul:
6279 case glslang::EOpSubgroupInclusiveMul:
6280 case glslang::EOpSubgroupExclusiveMul:
6281 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006282#ifdef NV_EXTENSIONS
6283 case glslang::EOpSubgroupPartitionedMul:
6284 case glslang::EOpSubgroupPartitionedInclusiveMul:
6285 case glslang::EOpSubgroupPartitionedExclusiveMul:
6286#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006287 if (isFloat) {
6288 opCode = spv::OpGroupNonUniformFMul;
6289 } else {
6290 opCode = spv::OpGroupNonUniformIMul;
6291 }
6292 break;
6293 case glslang::EOpSubgroupMin:
6294 case glslang::EOpSubgroupInclusiveMin:
6295 case glslang::EOpSubgroupExclusiveMin:
6296 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006297#ifdef NV_EXTENSIONS
6298 case glslang::EOpSubgroupPartitionedMin:
6299 case glslang::EOpSubgroupPartitionedInclusiveMin:
6300 case glslang::EOpSubgroupPartitionedExclusiveMin:
6301#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006302 if (isFloat) {
6303 opCode = spv::OpGroupNonUniformFMin;
6304 } else if (isUnsigned) {
6305 opCode = spv::OpGroupNonUniformUMin;
6306 } else {
6307 opCode = spv::OpGroupNonUniformSMin;
6308 }
6309 break;
6310 case glslang::EOpSubgroupMax:
6311 case glslang::EOpSubgroupInclusiveMax:
6312 case glslang::EOpSubgroupExclusiveMax:
6313 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006314#ifdef NV_EXTENSIONS
6315 case glslang::EOpSubgroupPartitionedMax:
6316 case glslang::EOpSubgroupPartitionedInclusiveMax:
6317 case glslang::EOpSubgroupPartitionedExclusiveMax:
6318#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006319 if (isFloat) {
6320 opCode = spv::OpGroupNonUniformFMax;
6321 } else if (isUnsigned) {
6322 opCode = spv::OpGroupNonUniformUMax;
6323 } else {
6324 opCode = spv::OpGroupNonUniformSMax;
6325 }
6326 break;
6327 case glslang::EOpSubgroupAnd:
6328 case glslang::EOpSubgroupInclusiveAnd:
6329 case glslang::EOpSubgroupExclusiveAnd:
6330 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006331#ifdef NV_EXTENSIONS
6332 case glslang::EOpSubgroupPartitionedAnd:
6333 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6334 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6335#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006336 if (isBool) {
6337 opCode = spv::OpGroupNonUniformLogicalAnd;
6338 } else {
6339 opCode = spv::OpGroupNonUniformBitwiseAnd;
6340 }
6341 break;
6342 case glslang::EOpSubgroupOr:
6343 case glslang::EOpSubgroupInclusiveOr:
6344 case glslang::EOpSubgroupExclusiveOr:
6345 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006346#ifdef NV_EXTENSIONS
6347 case glslang::EOpSubgroupPartitionedOr:
6348 case glslang::EOpSubgroupPartitionedInclusiveOr:
6349 case glslang::EOpSubgroupPartitionedExclusiveOr:
6350#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006351 if (isBool) {
6352 opCode = spv::OpGroupNonUniformLogicalOr;
6353 } else {
6354 opCode = spv::OpGroupNonUniformBitwiseOr;
6355 }
6356 break;
6357 case glslang::EOpSubgroupXor:
6358 case glslang::EOpSubgroupInclusiveXor:
6359 case glslang::EOpSubgroupExclusiveXor:
6360 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006361#ifdef NV_EXTENSIONS
6362 case glslang::EOpSubgroupPartitionedXor:
6363 case glslang::EOpSubgroupPartitionedInclusiveXor:
6364 case glslang::EOpSubgroupPartitionedExclusiveXor:
6365#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006366 if (isBool) {
6367 opCode = spv::OpGroupNonUniformLogicalXor;
6368 } else {
6369 opCode = spv::OpGroupNonUniformBitwiseXor;
6370 }
6371 break;
6372 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6373 case glslang::EOpSubgroupQuadSwapHorizontal:
6374 case glslang::EOpSubgroupQuadSwapVertical:
6375 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6376 default: assert(0 && "Unhandled subgroup operation!");
6377 }
6378
John Kessenich149afc32018-08-14 13:31:43 -06006379 // get the right Group Operation
6380 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006381 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006382 default:
6383 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006384 case glslang::EOpSubgroupBallotBitCount:
6385 case glslang::EOpSubgroupAdd:
6386 case glslang::EOpSubgroupMul:
6387 case glslang::EOpSubgroupMin:
6388 case glslang::EOpSubgroupMax:
6389 case glslang::EOpSubgroupAnd:
6390 case glslang::EOpSubgroupOr:
6391 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006392 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006393 break;
6394 case glslang::EOpSubgroupBallotInclusiveBitCount:
6395 case glslang::EOpSubgroupInclusiveAdd:
6396 case glslang::EOpSubgroupInclusiveMul:
6397 case glslang::EOpSubgroupInclusiveMin:
6398 case glslang::EOpSubgroupInclusiveMax:
6399 case glslang::EOpSubgroupInclusiveAnd:
6400 case glslang::EOpSubgroupInclusiveOr:
6401 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006402 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006403 break;
6404 case glslang::EOpSubgroupBallotExclusiveBitCount:
6405 case glslang::EOpSubgroupExclusiveAdd:
6406 case glslang::EOpSubgroupExclusiveMul:
6407 case glslang::EOpSubgroupExclusiveMin:
6408 case glslang::EOpSubgroupExclusiveMax:
6409 case glslang::EOpSubgroupExclusiveAnd:
6410 case glslang::EOpSubgroupExclusiveOr:
6411 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006412 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006413 break;
6414 case glslang::EOpSubgroupClusteredAdd:
6415 case glslang::EOpSubgroupClusteredMul:
6416 case glslang::EOpSubgroupClusteredMin:
6417 case glslang::EOpSubgroupClusteredMax:
6418 case glslang::EOpSubgroupClusteredAnd:
6419 case glslang::EOpSubgroupClusteredOr:
6420 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006421 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006422 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006423#ifdef NV_EXTENSIONS
6424 case glslang::EOpSubgroupPartitionedAdd:
6425 case glslang::EOpSubgroupPartitionedMul:
6426 case glslang::EOpSubgroupPartitionedMin:
6427 case glslang::EOpSubgroupPartitionedMax:
6428 case glslang::EOpSubgroupPartitionedAnd:
6429 case glslang::EOpSubgroupPartitionedOr:
6430 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006431 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006432 break;
6433 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6434 case glslang::EOpSubgroupPartitionedInclusiveMul:
6435 case glslang::EOpSubgroupPartitionedInclusiveMin:
6436 case glslang::EOpSubgroupPartitionedInclusiveMax:
6437 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6438 case glslang::EOpSubgroupPartitionedInclusiveOr:
6439 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006440 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006441 break;
6442 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6443 case glslang::EOpSubgroupPartitionedExclusiveMul:
6444 case glslang::EOpSubgroupPartitionedExclusiveMin:
6445 case glslang::EOpSubgroupPartitionedExclusiveMax:
6446 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6447 case glslang::EOpSubgroupPartitionedExclusiveOr:
6448 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006449 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006450 break;
6451#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006452 }
6453
John Kessenich149afc32018-08-14 13:31:43 -06006454 // build the instruction
6455 std::vector<spv::IdImmediate> spvGroupOperands;
6456
6457 // Every operation begins with the Execution Scope operand.
6458 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6459 spvGroupOperands.push_back(executionScope);
6460
6461 // Next, for all operations that use a Group Operation, push that as an operand.
6462 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006463 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006464 spvGroupOperands.push_back(groupOperand);
6465 }
6466
John Kessenich66011cb2018-03-06 16:12:04 -07006467 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006468 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6469 spv::IdImmediate operand = { true, *opIt };
6470 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006471 }
6472
6473 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006474 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006475 switch (op) {
6476 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006477 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6478 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6479 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6480 }
6481 if (directionId != spv::NoResult) {
6482 spv::IdImmediate direction = { true, directionId };
6483 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006484 }
6485
6486 return builder.createOp(opCode, typeId, spvGroupOperands);
6487}
6488
John Kessenich5e4b1242015-08-06 22:53:06 -06006489spv::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 -06006490{
John Kessenich66011cb2018-03-06 16:12:04 -07006491 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6492 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006493
John Kessenich140f3df2015-06-26 16:58:36 -06006494 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006495 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006496 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006497 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006498 spv::Id typeId0 = 0;
6499 if (consumedOperands > 0)
6500 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006501 spv::Id typeId1 = 0;
6502 if (consumedOperands > 1)
6503 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006504 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006505
6506 switch (op) {
6507 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006508 if (isFloat)
6509 libCall = spv::GLSLstd450FMin;
6510 else if (isUnsigned)
6511 libCall = spv::GLSLstd450UMin;
6512 else
6513 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006514 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006515 break;
6516 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006517 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006518 break;
6519 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006520 if (isFloat)
6521 libCall = spv::GLSLstd450FMax;
6522 else if (isUnsigned)
6523 libCall = spv::GLSLstd450UMax;
6524 else
6525 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006526 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006527 break;
6528 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006529 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006530 break;
6531 case glslang::EOpDot:
6532 opCode = spv::OpDot;
6533 break;
6534 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006535 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006536 break;
6537
6538 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006539 if (isFloat)
6540 libCall = spv::GLSLstd450FClamp;
6541 else if (isUnsigned)
6542 libCall = spv::GLSLstd450UClamp;
6543 else
6544 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006545 builder.promoteScalar(precision, operands.front(), operands[1]);
6546 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006547 break;
6548 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006549 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6550 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006551 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006552 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006553 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006554 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006555 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006556 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006557 break;
6558 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006559 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006560 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006561 break;
6562 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006563 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006564 builder.promoteScalar(precision, operands[0], operands[2]);
6565 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006566 break;
6567
6568 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006569 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006570 break;
6571 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006572 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006573 break;
6574 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006575 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006576 break;
6577 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006578 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006579 break;
6580 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006581 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006582 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006583 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006584#ifdef AMD_EXTENSIONS
6585 if (typeProxy == glslang::EbtFloat16)
6586 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6587#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006588 libCall = spv::GLSLstd450InterpolateAtSample;
6589 break;
6590 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006591#ifdef AMD_EXTENSIONS
6592 if (typeProxy == glslang::EbtFloat16)
6593 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6594#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006595 libCall = spv::GLSLstd450InterpolateAtOffset;
6596 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006597 case glslang::EOpAddCarry:
6598 opCode = spv::OpIAddCarry;
6599 typeId = builder.makeStructResultType(typeId0, typeId0);
6600 consumedOperands = 2;
6601 break;
6602 case glslang::EOpSubBorrow:
6603 opCode = spv::OpISubBorrow;
6604 typeId = builder.makeStructResultType(typeId0, typeId0);
6605 consumedOperands = 2;
6606 break;
6607 case glslang::EOpUMulExtended:
6608 opCode = spv::OpUMulExtended;
6609 typeId = builder.makeStructResultType(typeId0, typeId0);
6610 consumedOperands = 2;
6611 break;
6612 case glslang::EOpIMulExtended:
6613 opCode = spv::OpSMulExtended;
6614 typeId = builder.makeStructResultType(typeId0, typeId0);
6615 consumedOperands = 2;
6616 break;
6617 case glslang::EOpBitfieldExtract:
6618 if (isUnsigned)
6619 opCode = spv::OpBitFieldUExtract;
6620 else
6621 opCode = spv::OpBitFieldSExtract;
6622 break;
6623 case glslang::EOpBitfieldInsert:
6624 opCode = spv::OpBitFieldInsert;
6625 break;
6626
6627 case glslang::EOpFma:
6628 libCall = spv::GLSLstd450Fma;
6629 break;
6630 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006631 {
6632 libCall = spv::GLSLstd450FrexpStruct;
6633 assert(builder.isPointerType(typeId1));
6634 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006635 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006636#ifdef AMD_EXTENSIONS
6637 if (width == 16)
6638 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6639 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6640#endif
Rex Xu470026f2017-03-29 17:12:40 +08006641 if (builder.getNumComponents(operands[0]) == 1)
6642 frexpIntType = builder.makeIntegerType(width, true);
6643 else
6644 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6645 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6646 consumedOperands = 1;
6647 }
John Kessenich55e7d112015-11-15 21:33:39 -07006648 break;
6649 case glslang::EOpLdexp:
6650 libCall = spv::GLSLstd450Ldexp;
6651 break;
6652
Rex Xu574ab042016-04-14 16:53:07 +08006653 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006654 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006655
John Kessenich66011cb2018-03-06 16:12:04 -07006656 case glslang::EOpSubgroupBroadcast:
6657 case glslang::EOpSubgroupBallotBitExtract:
6658 case glslang::EOpSubgroupShuffle:
6659 case glslang::EOpSubgroupShuffleXor:
6660 case glslang::EOpSubgroupShuffleUp:
6661 case glslang::EOpSubgroupShuffleDown:
6662 case glslang::EOpSubgroupClusteredAdd:
6663 case glslang::EOpSubgroupClusteredMul:
6664 case glslang::EOpSubgroupClusteredMin:
6665 case glslang::EOpSubgroupClusteredMax:
6666 case glslang::EOpSubgroupClusteredAnd:
6667 case glslang::EOpSubgroupClusteredOr:
6668 case glslang::EOpSubgroupClusteredXor:
6669 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006670#ifdef NV_EXTENSIONS
6671 case glslang::EOpSubgroupPartitionedAdd:
6672 case glslang::EOpSubgroupPartitionedMul:
6673 case glslang::EOpSubgroupPartitionedMin:
6674 case glslang::EOpSubgroupPartitionedMax:
6675 case glslang::EOpSubgroupPartitionedAnd:
6676 case glslang::EOpSubgroupPartitionedOr:
6677 case glslang::EOpSubgroupPartitionedXor:
6678 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6679 case glslang::EOpSubgroupPartitionedInclusiveMul:
6680 case glslang::EOpSubgroupPartitionedInclusiveMin:
6681 case glslang::EOpSubgroupPartitionedInclusiveMax:
6682 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6683 case glslang::EOpSubgroupPartitionedInclusiveOr:
6684 case glslang::EOpSubgroupPartitionedInclusiveXor:
6685 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6686 case glslang::EOpSubgroupPartitionedExclusiveMul:
6687 case glslang::EOpSubgroupPartitionedExclusiveMin:
6688 case glslang::EOpSubgroupPartitionedExclusiveMax:
6689 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6690 case glslang::EOpSubgroupPartitionedExclusiveOr:
6691 case glslang::EOpSubgroupPartitionedExclusiveXor:
6692#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006693 return createSubgroupOperation(op, typeId, operands, typeProxy);
6694
Rex Xu9d93a232016-05-05 12:30:44 +08006695#ifdef AMD_EXTENSIONS
6696 case glslang::EOpSwizzleInvocations:
6697 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6698 libCall = spv::SwizzleInvocationsAMD;
6699 break;
6700 case glslang::EOpSwizzleInvocationsMasked:
6701 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6702 libCall = spv::SwizzleInvocationsMaskedAMD;
6703 break;
6704 case glslang::EOpWriteInvocation:
6705 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6706 libCall = spv::WriteInvocationAMD;
6707 break;
6708
6709 case glslang::EOpMin3:
6710 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6711 if (isFloat)
6712 libCall = spv::FMin3AMD;
6713 else {
6714 if (isUnsigned)
6715 libCall = spv::UMin3AMD;
6716 else
6717 libCall = spv::SMin3AMD;
6718 }
6719 break;
6720 case glslang::EOpMax3:
6721 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6722 if (isFloat)
6723 libCall = spv::FMax3AMD;
6724 else {
6725 if (isUnsigned)
6726 libCall = spv::UMax3AMD;
6727 else
6728 libCall = spv::SMax3AMD;
6729 }
6730 break;
6731 case glslang::EOpMid3:
6732 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6733 if (isFloat)
6734 libCall = spv::FMid3AMD;
6735 else {
6736 if (isUnsigned)
6737 libCall = spv::UMid3AMD;
6738 else
6739 libCall = spv::SMid3AMD;
6740 }
6741 break;
6742
6743 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006744 if (typeProxy == glslang::EbtFloat16)
6745 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006746 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6747 libCall = spv::InterpolateAtVertexAMD;
6748 break;
6749#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006750 case glslang::EOpBarrier:
6751 {
6752 // This is for the extended controlBarrier function, with four operands.
6753 // The unextended barrier() goes through createNoArgOperation.
6754 assert(operands.size() == 4);
6755 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6756 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6757 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6758 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6759 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6760 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6761 }
6762 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6763 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6764 }
6765 return 0;
6766 }
6767 break;
6768 case glslang::EOpMemoryBarrier:
6769 {
6770 // This is for the extended memoryBarrier function, with three operands.
6771 // The unextended memoryBarrier() goes through createNoArgOperation.
6772 assert(operands.size() == 3);
6773 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6774 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6775 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6776 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6777 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6778 }
6779 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6780 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6781 }
6782 return 0;
6783 }
6784 break;
Chao Chen3c366992018-09-19 11:41:59 -07006785
6786#ifdef NV_EXTENSIONS
6787 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6788 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6789 return 0;
6790#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006791 default:
6792 return 0;
6793 }
6794
6795 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006796 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006797 // Use an extended instruction from the standard library.
6798 // Construct the call arguments, without modifying the original operands vector.
6799 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6800 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006801 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006802 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006803 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006804 case 0:
6805 // should all be handled by visitAggregate and createNoArgOperation
6806 assert(0);
6807 return 0;
6808 case 1:
6809 // should all be handled by createUnaryOperation
6810 assert(0);
6811 return 0;
6812 case 2:
6813 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6814 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006815 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006816 // anything 3 or over doesn't have l-value operands, so all should be consumed
6817 assert(consumedOperands == operands.size());
6818 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006819 break;
6820 }
6821 }
6822
John Kessenich55e7d112015-11-15 21:33:39 -07006823 // Decode the return types that were structures
6824 switch (op) {
6825 case glslang::EOpAddCarry:
6826 case glslang::EOpSubBorrow:
6827 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6828 id = builder.createCompositeExtract(id, typeId0, 0);
6829 break;
6830 case glslang::EOpUMulExtended:
6831 case glslang::EOpIMulExtended:
6832 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6833 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6834 break;
6835 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006836 {
6837 assert(operands.size() == 2);
6838 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6839 // "exp" is floating-point type (from HLSL intrinsic)
6840 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6841 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6842 builder.createStore(member1, operands[1]);
6843 } else
6844 // "exp" is integer type (from GLSL built-in function)
6845 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6846 id = builder.createCompositeExtract(id, typeId0, 0);
6847 }
John Kessenich55e7d112015-11-15 21:33:39 -07006848 break;
6849 default:
6850 break;
6851 }
6852
John Kessenich32cfd492016-02-02 12:37:46 -07006853 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006854}
6855
Rex Xu9d93a232016-05-05 12:30:44 +08006856// Intrinsics with no arguments (or no return value, and no precision).
6857spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006858{
Jeff Bolz36831c92018-09-05 10:11:41 -05006859 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6860 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006861
6862 switch (op) {
6863 case glslang::EOpEmitVertex:
6864 builder.createNoResultOp(spv::OpEmitVertex);
6865 return 0;
6866 case glslang::EOpEndPrimitive:
6867 builder.createNoResultOp(spv::OpEndPrimitive);
6868 return 0;
6869 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006870 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006871 if (glslangIntermediate->usingVulkanMemoryModel()) {
6872 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6873 spv::MemorySemanticsOutputMemoryKHRMask |
6874 spv::MemorySemanticsAcquireReleaseMask);
6875 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6876 } else {
6877 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6878 }
John Kessenich82979362017-12-11 04:02:24 -07006879 } else {
6880 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6881 spv::MemorySemanticsWorkgroupMemoryMask |
6882 spv::MemorySemanticsAcquireReleaseMask);
6883 }
John Kessenich140f3df2015-06-26 16:58:36 -06006884 return 0;
6885 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006886 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6887 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006888 return 0;
6889 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006890 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6891 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006892 return 0;
6893 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006894 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6895 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006896 return 0;
6897 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006898 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6899 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006900 return 0;
6901 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006902 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6903 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006904 return 0;
6905 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006906 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6907 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006908 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006909 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006910 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006911 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006912 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006913 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006914 case glslang::EOpDeviceMemoryBarrier:
6915 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6916 spv::MemorySemanticsImageMemoryMask |
6917 spv::MemorySemanticsAcquireReleaseMask);
6918 return 0;
6919 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6920 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6921 spv::MemorySemanticsImageMemoryMask |
6922 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006923 return 0;
6924 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006925 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6926 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006927 return 0;
6928 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006929 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6930 spv::MemorySemanticsWorkgroupMemoryMask |
6931 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006932 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006933 case glslang::EOpSubgroupBarrier:
6934 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6935 spv::MemorySemanticsAcquireReleaseMask);
6936 return spv::NoResult;
6937 case glslang::EOpSubgroupMemoryBarrier:
6938 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6939 spv::MemorySemanticsAcquireReleaseMask);
6940 return spv::NoResult;
6941 case glslang::EOpSubgroupMemoryBarrierBuffer:
6942 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6943 spv::MemorySemanticsAcquireReleaseMask);
6944 return spv::NoResult;
6945 case glslang::EOpSubgroupMemoryBarrierImage:
6946 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6947 spv::MemorySemanticsAcquireReleaseMask);
6948 return spv::NoResult;
6949 case glslang::EOpSubgroupMemoryBarrierShared:
6950 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6951 spv::MemorySemanticsAcquireReleaseMask);
6952 return spv::NoResult;
6953 case glslang::EOpSubgroupElect: {
6954 std::vector<spv::Id> operands;
6955 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6956 }
Rex Xu9d93a232016-05-05 12:30:44 +08006957#ifdef AMD_EXTENSIONS
6958 case glslang::EOpTime:
6959 {
6960 std::vector<spv::Id> args; // Dummy arguments
6961 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6962 return builder.setPrecision(id, precision);
6963 }
6964#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006965 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006966 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006967 return 0;
6968 }
6969}
6970
6971spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6972{
John Kessenich2f273362015-07-18 22:34:27 -06006973 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006974 spv::Id id;
6975 if (symbolValues.end() != iter) {
6976 id = iter->second;
6977 return id;
6978 }
6979
6980 // it was not found, create it
6981 id = createSpvVariable(symbol);
6982 symbolValues[symbol->getId()] = id;
6983
Rex Xuc884b4a2016-06-29 15:03:44 +08006984 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006985 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6986 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6987 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07006988#ifdef NV_EXTENSIONS
6989 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
6990#endif
John Kessenich6c292d32016-02-15 20:58:50 -07006991 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006992 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006993 if (symbol->getQualifier().hasIndex())
6994 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6995 if (symbol->getQualifier().hasComponent())
6996 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006997 // atomic counters use this:
6998 if (symbol->getQualifier().hasOffset())
6999 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007000 }
7001
scygan2c864272016-05-18 18:09:17 +02007002 if (symbol->getQualifier().hasLocation())
7003 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007004 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007005 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007006 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007007 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007008 }
John Kessenich140f3df2015-06-26 16:58:36 -06007009 if (symbol->getQualifier().hasSet())
7010 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007011 else if (IsDescriptorResource(symbol->getType())) {
7012 // default to 0
7013 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7014 }
John Kessenich140f3df2015-06-26 16:58:36 -06007015 if (symbol->getQualifier().hasBinding())
7016 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07007017 if (symbol->getQualifier().hasAttachment())
7018 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007019 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007020 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06007021 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06007022 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07007023 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007024 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007025 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7026 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7027 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7028 }
7029 if (symbol->getQualifier().hasXfbOffset())
7030 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007031 }
7032
Rex Xu1da878f2016-02-21 20:59:01 +08007033 if (symbol->getType().isImage()) {
7034 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007035 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007036 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007037 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007038 }
7039
John Kessenich140f3df2015-06-26 16:58:36 -06007040 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007041 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007042 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007043 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007044
John Kessenich5611c6d2018-04-05 11:25:02 -06007045 // nonuniform
7046 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7047
John Kessenichecba76f2017-01-06 00:34:48 -07007048#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007049 if (builtIn == spv::BuiltInSampleMask) {
7050 spv::Decoration decoration;
7051 // GL_NV_sample_mask_override_coverage extension
7052 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007053 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007054 else
7055 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007056 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007057 if (decoration != spv::DecorationMax) {
7058 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7059 }
7060 }
chaoc771d89f2017-01-13 01:10:53 -08007061 else if (builtIn == spv::BuiltInLayer) {
7062 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007063 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007064 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007065 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7066 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7067 }
John Kessenichb41bff62017-08-11 13:07:17 -06007068 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007069 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7070 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007071 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7072 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7073 }
7074 }
7075
chaoc6e5acae2016-12-20 13:28:52 -08007076 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007077 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007078 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007079 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7080 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007081 if (symbol->getQualifier().pervertexNV) {
7082 builder.addDecoration(id, spv::DecorationPerVertexNV);
7083 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7084 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7085 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007086#endif
7087
John Kessenich5d610ee2018-03-07 18:05:55 -07007088 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7089 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7090 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7091 symbol->getType().getQualifier().semanticName);
7092 }
7093
John Kessenich140f3df2015-06-26 16:58:36 -06007094 return id;
7095}
7096
Chao Chen3c366992018-09-19 11:41:59 -07007097#ifdef NV_EXTENSIONS
7098// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7099void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7100{
7101 if (member >= 0) {
7102 if (qualifier.perPrimitiveNV)
7103 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
7104 if (qualifier.perViewNV)
7105 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7106 if (qualifier.perTaskNV)
7107 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7108 } else {
7109 if (qualifier.perPrimitiveNV)
7110 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
7111 if (qualifier.perViewNV)
7112 builder.addDecoration(id, spv::DecorationPerViewNV);
7113 if (qualifier.perTaskNV)
7114 builder.addDecoration(id, spv::DecorationPerTaskNV);
7115 }
7116}
7117#endif
7118
John Kessenich55e7d112015-11-15 21:33:39 -07007119// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007120// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007121//
7122// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7123//
7124// Recursively walk the nodes. The nodes form a tree whose leaves are
7125// regular constants, which themselves are trees that createSpvConstant()
7126// recursively walks. So, this function walks the "top" of the tree:
7127// - emit specialization constant-building instructions for specConstant
7128// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007129spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007130{
John Kessenich7cc0e282016-03-20 00:46:02 -06007131 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007132
qining4f4bb812016-04-03 23:55:17 -04007133 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007134 if (! node.getQualifier().specConstant) {
7135 // hand off to the non-spec-constant path
7136 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7137 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007138 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007139 nextConst, false);
7140 }
7141
7142 // We now know we have a specialization constant to build
7143
John Kessenichd94c0032016-05-30 19:29:40 -06007144 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007145 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7146 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7147 std::vector<spv::Id> dimConstId;
7148 for (int dim = 0; dim < 3; ++dim) {
7149 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7150 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007151 if (specConst) {
7152 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7153 glslangIntermediate->getLocalSizeSpecId(dim));
7154 }
qining4f4bb812016-04-03 23:55:17 -04007155 }
7156 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7157 }
7158
7159 // An AST node labelled as specialization constant should be a symbol node.
7160 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7161 if (auto* sn = node.getAsSymbolNode()) {
7162 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007163 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7164 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7165 // will set the builder into spec constant op instruction generating mode.
7166 sub_tree->traverse(this);
7167 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04007168 } else if (auto* const_union_array = &sn->getConstArray()){
7169 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01007170 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
7171 builder.addName(id, sn->getName().c_str());
7172 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07007173 }
7174 }
qining4f4bb812016-04-03 23:55:17 -04007175
7176 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7177 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007178 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007179 exit(1);
7180 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007181}
7182
John Kessenich140f3df2015-06-26 16:58:36 -06007183// Use 'consts' as the flattened glslang source of scalar constants to recursively
7184// build the aggregate SPIR-V constant.
7185//
7186// If there are not enough elements present in 'consts', 0 will be substituted;
7187// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7188//
qining08408382016-03-21 09:51:37 -04007189spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007190{
7191 // vector of constants for SPIR-V
7192 std::vector<spv::Id> spvConsts;
7193
7194 // Type is used for struct and array constants
7195 spv::Id typeId = convertGlslangToSpvType(glslangType);
7196
7197 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007198 glslang::TType elementType(glslangType, 0);
7199 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007200 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007201 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007202 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007203 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007204 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007205 } else if (glslangType.getStruct()) {
7206 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7207 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007208 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007209 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007210 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7211 bool zero = nextConst >= consts.size();
7212 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007213 case glslang::EbtInt8:
7214 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7215 break;
7216 case glslang::EbtUint8:
7217 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7218 break;
7219 case glslang::EbtInt16:
7220 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7221 break;
7222 case glslang::EbtUint16:
7223 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7224 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007225 case glslang::EbtInt:
7226 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7227 break;
7228 case glslang::EbtUint:
7229 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7230 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007231 case glslang::EbtInt64:
7232 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7233 break;
7234 case glslang::EbtUint64:
7235 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7236 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007237 case glslang::EbtFloat:
7238 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7239 break;
7240 case glslang::EbtDouble:
7241 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7242 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007243 case glslang::EbtFloat16:
7244 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007246 case glslang::EbtBool:
7247 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7248 break;
7249 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007251 break;
7252 }
7253 ++nextConst;
7254 }
7255 } else {
7256 // we have a non-aggregate (scalar) constant
7257 bool zero = nextConst >= consts.size();
7258 spv::Id scalar = 0;
7259 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007260 case glslang::EbtInt8:
7261 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7262 break;
7263 case glslang::EbtUint8:
7264 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7265 break;
7266 case glslang::EbtInt16:
7267 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7268 break;
7269 case glslang::EbtUint16:
7270 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7271 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007272 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007273 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007274 break;
7275 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007276 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007277 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007278 case glslang::EbtInt64:
7279 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7280 break;
7281 case glslang::EbtUint64:
7282 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7283 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007284 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007285 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007286 break;
7287 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007288 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007289 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007290 case glslang::EbtFloat16:
7291 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7292 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007293 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007294 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007295 break;
7296 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007298 break;
7299 }
7300 ++nextConst;
7301 return scalar;
7302 }
7303
7304 return builder.makeCompositeConstant(typeId, spvConsts);
7305}
7306
John Kessenich7c1aa102015-10-15 13:29:11 -06007307// Return true if the node is a constant or symbol whose reading has no
7308// non-trivial observable cost or effect.
7309bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7310{
7311 // don't know what this is
7312 if (node == nullptr)
7313 return false;
7314
7315 // a constant is safe
7316 if (node->getAsConstantUnion() != nullptr)
7317 return true;
7318
7319 // not a symbol means non-trivial
7320 if (node->getAsSymbolNode() == nullptr)
7321 return false;
7322
7323 // a symbol, depends on what's being read
7324 switch (node->getType().getQualifier().storage) {
7325 case glslang::EvqTemporary:
7326 case glslang::EvqGlobal:
7327 case glslang::EvqIn:
7328 case glslang::EvqInOut:
7329 case glslang::EvqConst:
7330 case glslang::EvqConstReadOnly:
7331 case glslang::EvqUniform:
7332 return true;
7333 default:
7334 return false;
7335 }
qining25262b32016-05-06 17:25:16 -04007336}
John Kessenich7c1aa102015-10-15 13:29:11 -06007337
7338// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007339// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007340// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007341// Return true if trivial.
7342bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7343{
7344 if (node == nullptr)
7345 return false;
7346
John Kessenich84cc15f2017-05-24 16:44:47 -06007347 // count non scalars as trivial, as well as anything coming from HLSL
7348 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007349 return true;
7350
John Kessenich7c1aa102015-10-15 13:29:11 -06007351 // symbols and constants are trivial
7352 if (isTrivialLeaf(node))
7353 return true;
7354
7355 // otherwise, it needs to be a simple operation or one or two leaf nodes
7356
7357 // not a simple operation
7358 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7359 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7360 if (binaryNode == nullptr && unaryNode == nullptr)
7361 return false;
7362
7363 // not on leaf nodes
7364 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7365 return false;
7366
7367 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7368 return false;
7369 }
7370
7371 switch (node->getAsOperator()->getOp()) {
7372 case glslang::EOpLogicalNot:
7373 case glslang::EOpConvIntToBool:
7374 case glslang::EOpConvUintToBool:
7375 case glslang::EOpConvFloatToBool:
7376 case glslang::EOpConvDoubleToBool:
7377 case glslang::EOpEqual:
7378 case glslang::EOpNotEqual:
7379 case glslang::EOpLessThan:
7380 case glslang::EOpGreaterThan:
7381 case glslang::EOpLessThanEqual:
7382 case glslang::EOpGreaterThanEqual:
7383 case glslang::EOpIndexDirect:
7384 case glslang::EOpIndexDirectStruct:
7385 case glslang::EOpLogicalXor:
7386 case glslang::EOpAny:
7387 case glslang::EOpAll:
7388 return true;
7389 default:
7390 return false;
7391 }
7392}
7393
7394// Emit short-circuiting code, where 'right' is never evaluated unless
7395// the left side is true (for &&) or false (for ||).
7396spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7397{
7398 spv::Id boolTypeId = builder.makeBoolType();
7399
7400 // emit left operand
7401 builder.clearAccessChain();
7402 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007403 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007404
7405 // Operands to accumulate OpPhi operands
7406 std::vector<spv::Id> phiOperands;
7407 // accumulate left operand's phi information
7408 phiOperands.push_back(leftId);
7409 phiOperands.push_back(builder.getBuildPoint()->getId());
7410
7411 // Make the two kinds of operation symmetric with a "!"
7412 // || => emit "if (! left) result = right"
7413 // && => emit "if ( left) result = right"
7414 //
7415 // TODO: this runtime "not" for || could be avoided by adding functionality
7416 // to 'builder' to have an "else" without an "then"
7417 if (op == glslang::EOpLogicalOr)
7418 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7419
7420 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007421 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007422
7423 // emit right operand as the "then" part of the "if"
7424 builder.clearAccessChain();
7425 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007426 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007427
7428 // accumulate left operand's phi information
7429 phiOperands.push_back(rightId);
7430 phiOperands.push_back(builder.getBuildPoint()->getId());
7431
7432 // finish the "if"
7433 ifBuilder.makeEndIf();
7434
7435 // phi together the two results
7436 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7437}
7438
Frank Henigman541f7bb2018-01-16 00:18:26 -05007439#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007440// Return type Id of the imported set of extended instructions corresponds to the name.
7441// Import this set if it has not been imported yet.
7442spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7443{
7444 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7445 return extBuiltinMap[name];
7446 else {
Rex Xu51596642016-09-21 18:56:12 +08007447 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007448 spv::Id extBuiltins = builder.import(name);
7449 extBuiltinMap[name] = extBuiltins;
7450 return extBuiltins;
7451 }
7452}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007453#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007454
John Kessenich140f3df2015-06-26 16:58:36 -06007455}; // end anonymous namespace
7456
7457namespace glslang {
7458
John Kessenich68d78fd2015-07-12 19:28:10 -06007459void GetSpirvVersion(std::string& version)
7460{
John Kessenich9e55f632015-07-15 10:03:39 -06007461 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007462 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007463 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007464 version = buf;
7465}
7466
John Kessenicha372a3e2017-11-02 22:32:14 -06007467// For low-order part of the generator's magic number. Bump up
7468// when there is a change in the style (e.g., if SSA form changes,
7469// or a different instruction sequence to do something gets used).
7470int GetSpirvGeneratorVersion()
7471{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007472 // return 1; // start
7473 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007474 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007475 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007476 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007477 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7478 // versions 4 and 6 each generate OpArrayLength as it has long been done
7479 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007480}
7481
John Kessenich140f3df2015-06-26 16:58:36 -06007482// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007483void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007484{
7485 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007486 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007487 if (out.fail())
7488 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007489 for (int i = 0; i < (int)spirv.size(); ++i) {
7490 unsigned int word = spirv[i];
7491 out.write((const char*)&word, 4);
7492 }
7493 out.close();
7494}
7495
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007496// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007497void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007498{
7499 std::ofstream out;
7500 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007501 if (out.fail())
7502 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007503 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007504 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007505 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007506 if (varName != nullptr) {
7507 out << "\t #pragma once" << std::endl;
7508 out << "const uint32_t " << varName << "[] = {" << std::endl;
7509 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007510 const int WORDS_PER_LINE = 8;
7511 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7512 out << "\t";
7513 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7514 const unsigned int word = spirv[i + j];
7515 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7516 if (i + j + 1 < (int)spirv.size()) {
7517 out << ",";
7518 }
7519 }
7520 out << std::endl;
7521 }
Flavio15017db2017-02-15 14:29:33 -08007522 if (varName != nullptr) {
7523 out << "};";
7524 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007525 out.close();
7526}
7527
John Kessenich140f3df2015-06-26 16:58:36 -06007528//
7529// Set up the glslang traversal
7530//
John Kessenich4e11b612018-08-30 16:56:59 -06007531void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007532{
Lei Zhang17535f72016-05-04 15:55:59 -04007533 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007534 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007535}
7536
John Kessenich4e11b612018-08-30 16:56:59 -06007537void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007538 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007539{
John Kessenich140f3df2015-06-26 16:58:36 -06007540 TIntermNode* root = intermediate.getTreeRoot();
7541
7542 if (root == 0)
7543 return;
7544
John Kessenich4e11b612018-08-30 16:56:59 -06007545 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007546 if (options == nullptr)
7547 options = &defaultOptions;
7548
John Kessenich4e11b612018-08-30 16:56:59 -06007549 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007550
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007551 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007552 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007553 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007554 it.dumpSpv(spirv);
7555
GregFfb03a552018-03-29 11:49:14 -06007556#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007557 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7558 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007559 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007560 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007561
John Kessenich4e11b612018-08-30 16:56:59 -06007562 if (options->validate)
7563 SpirvToolsValidate(intermediate, spirv, logger);
7564
John Kessenich717c80a2018-08-23 15:17:10 -06007565 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007566 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007567
GregFcd1f1692017-09-21 18:40:22 -06007568#endif
7569
John Kessenich4e11b612018-08-30 16:56:59 -06007570 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007571}
7572
7573}; // end namespace glslang