blob: 2ddece12ea5cde37867a24ecd1a418daf629e452 [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.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 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);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600150 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
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
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600214 unsigned int getBufferReferenceAlignment(const glslang::TType &type) const {
215 if (type.getBasicType() == glslang::EbtReference) {
216 return type.getReferentType()->getQualifier().hasBufferReferenceAlign() ?
217 (1u << type.getReferentType()->getQualifier().layoutBufferReferenceAlign) : 16u;
218 } else {
219 return 0;
220 }
221 }
222
John Kessenich121853f2017-05-31 17:11:16 -0600223 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600224 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600225 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700226 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 int sequenceDepth;
228
Lei Zhang17535f72016-05-04 15:55:59 -0400229 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400230
John Kessenich140f3df2015-06-26 16:58:36 -0600231 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
232 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700233 bool inEntryPoint;
234 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700235 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 -0700236 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600237 const glslang::TIntermediate* glslangIntermediate;
238 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800239 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600240
John Kessenich2f273362015-07-18 22:34:27 -0600241 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600242 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600243 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700244 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700245 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
246 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600247 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700248 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600249 // Map pointee types for EbtReference to their forward pointers
250 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600251};
252
253//
254// Helper functions for translating glslang representations to SPIR-V enumerants.
255//
256
257// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700258spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600259{
John Kessenich66e2faf2016-03-12 18:34:36 -0700260 switch (source) {
261 case glslang::EShSourceGlsl:
262 switch (profile) {
263 case ENoProfile:
264 case ECoreProfile:
265 case ECompatibilityProfile:
266 return spv::SourceLanguageGLSL;
267 case EEsProfile:
268 return spv::SourceLanguageESSL;
269 default:
270 return spv::SourceLanguageUnknown;
271 }
272 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600273 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::SourceLanguageUnknown;
276 }
277}
278
279// Translate glslang language (stage) to SPIR-V execution model.
280spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
281{
282 switch (stage) {
283 case EShLangVertex: return spv::ExecutionModelVertex;
284 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
285 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
286 case EShLangGeometry: return spv::ExecutionModelGeometry;
287 case EShLangFragment: return spv::ExecutionModelFragment;
288 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700289#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700290 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
291 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
292 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
293 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
294 case EShLangMissNV: return spv::ExecutionModelMissNV;
295 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700296 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
297 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
298#endif
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::ExecutionModelFragment;
302 }
303}
304
John Kessenich140f3df2015-06-26 16:58:36 -0600305// Translate glslang sampler type to SPIR-V dimensionality.
306spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
307{
308 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700309 case glslang::Esd1D: return spv::Dim1D;
310 case glslang::Esd2D: return spv::Dim2D;
311 case glslang::Esd3D: return spv::Dim3D;
312 case glslang::EsdCube: return spv::DimCube;
313 case glslang::EsdRect: return spv::DimRect;
314 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700315 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 return spv::Dim2D;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang precision to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600324{
John Kessenichf6640762016-08-01 19:44:00 -0600325 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700326 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600327 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 default:
329 return spv::NoPrecision;
330 }
331}
332
John Kessenichf6640762016-08-01 19:44:00 -0600333// Translate glslang type to SPIR-V precision decorations.
334spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
335{
336 return TranslatePrecisionDecoration(type.getQualifier().precision);
337}
338
John Kessenich140f3df2015-06-26 16:58:36 -0600339// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600340spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600341{
342 if (type.getBasicType() == glslang::EbtBlock) {
343 switch (type.getQualifier().storage) {
344 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600345 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::EvqVaryingIn: return spv::DecorationBlock;
347 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700348#ifdef NV_EXTENSIONS
349 case glslang::EvqPayloadNV: return spv::DecorationBlock;
350 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
351 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700352 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
353 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700354#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600355 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700356 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600357 break;
358 }
359 }
360
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362}
363
Rex Xu1da878f2016-02-21 20:59:01 +0800364// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500365void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800366{
Jeff Bolz36831c92018-09-05 10:11:41 -0500367 if (!useVulkanMemoryModel) {
368 if (qualifier.coherent)
369 memory.push_back(spv::DecorationCoherent);
370 if (qualifier.volatil) {
371 memory.push_back(spv::DecorationVolatile);
372 memory.push_back(spv::DecorationCoherent);
373 }
John Kessenich14b85d32018-06-04 15:36:03 -0600374 }
Rex Xu1da878f2016-02-21 20:59:01 +0800375 if (qualifier.restrict)
376 memory.push_back(spv::DecorationRestrict);
377 if (qualifier.readonly)
378 memory.push_back(spv::DecorationNonWritable);
379 if (qualifier.writeonly)
380 memory.push_back(spv::DecorationNonReadable);
381}
382
John Kessenich140f3df2015-06-26 16:58:36 -0600383// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700384spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600385{
386 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700387 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600388 case glslang::ElmRowMajor:
389 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700390 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700392 default:
393 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600394 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 }
396 } else {
397 switch (type.getBasicType()) {
398 default:
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600400 break;
401 case glslang::EbtBlock:
402 switch (type.getQualifier().storage) {
403 case glslang::EvqUniform:
404 case glslang::EvqBuffer:
405 switch (type.getQualifier().layoutPacking) {
406 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
408 default:
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410 }
411 case glslang::EvqVaryingIn:
412 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700413 if (type.getQualifier().isTaskMemory()) {
414 switch (type.getQualifier().layoutPacking) {
415 case glslang::ElpShared: return spv::DecorationGLSLShared;
416 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
417 default: break;
418 }
419 } else {
420 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
421 }
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700423#ifdef NV_EXTENSIONS
424 case glslang::EvqPayloadNV:
425 case glslang::EvqPayloadInNV:
426 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700427 case glslang::EvqCallableDataNV:
428 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700429 return spv::DecorationMax;
430#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600431 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700432 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600433 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600434 }
435 }
436 }
437}
438
439// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600440// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700441// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800442spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600443{
Rex Xubbceed72016-05-21 09:40:44 +0800444 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700445 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600446 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800447 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700448 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700449 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600450 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800451#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800452 else if (qualifier.explicitInterp) {
453 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800454 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800455 }
Rex Xu9d93a232016-05-05 12:30:44 +0800456#endif
Rex Xubbceed72016-05-21 09:40:44 +0800457 else
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800459}
460
461// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600462// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800463// should be applied.
464spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
465{
466 if (qualifier.patch)
467 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700468 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600469 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700470 else if (qualifier.sample) {
471 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600472 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700473 } else
John Kessenich4016e382016-07-15 11:53:56 -0600474 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600475}
476
John Kessenich92187592016-02-01 13:45:25 -0700477// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700478spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600479{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700480 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600481 return spv::DecorationInvariant;
482 else
John Kessenich4016e382016-07-15 11:53:56 -0600483 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600484}
485
qining9220dbb2016-05-04 17:34:38 -0400486// If glslang type is noContraction, return SPIR-V NoContraction decoration.
487spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
488{
489 if (qualifier.noContraction)
490 return spv::DecorationNoContraction;
491 else
John Kessenich4016e382016-07-15 11:53:56 -0600492 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400493}
494
John Kessenich5611c6d2018-04-05 11:25:02 -0600495// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
496spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
497{
498 if (qualifier.isNonUniform()) {
499 builder.addExtension("SPV_EXT_descriptor_indexing");
500 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
501 return spv::DecorationNonUniformEXT;
502 } else
503 return spv::DecorationMax;
504}
505
Jeff Bolz36831c92018-09-05 10:11:41 -0500506spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
507{
508 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
509 return spv::MemoryAccessMaskNone;
510 }
511 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
512 if (coherentFlags.volatil ||
513 coherentFlags.coherent ||
514 coherentFlags.devicecoherent ||
515 coherentFlags.queuefamilycoherent ||
516 coherentFlags.workgroupcoherent ||
517 coherentFlags.subgroupcoherent) {
518 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
519 spv::MemoryAccessMakePointerVisibleKHRMask;
520 }
521 if (coherentFlags.nonprivate) {
522 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
523 }
524 if (coherentFlags.volatil) {
525 mask = mask | spv::MemoryAccessVolatileMask;
526 }
527 if (mask != spv::MemoryAccessMaskNone) {
528 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
529 }
530 return mask;
531}
532
533spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
534{
535 if (!glslangIntermediate->usingVulkanMemoryModel()) {
536 return spv::ImageOperandsMaskNone;
537 }
538 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
539 if (coherentFlags.volatil ||
540 coherentFlags.coherent ||
541 coherentFlags.devicecoherent ||
542 coherentFlags.queuefamilycoherent ||
543 coherentFlags.workgroupcoherent ||
544 coherentFlags.subgroupcoherent) {
545 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
546 spv::ImageOperandsMakeTexelVisibleKHRMask;
547 }
548 if (coherentFlags.nonprivate) {
549 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
550 }
551 if (coherentFlags.volatil) {
552 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
553 }
554 if (mask != spv::ImageOperandsMaskNone) {
555 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
556 }
557 return mask;
558}
559
560spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
561{
562 spv::Builder::AccessChain::CoherentFlags flags;
563 flags.coherent = type.getQualifier().coherent;
564 flags.devicecoherent = type.getQualifier().devicecoherent;
565 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
566 // shared variables are implicitly workgroupcoherent in GLSL.
567 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
568 type.getQualifier().storage == glslang::EvqShared;
569 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
570 // *coherent variables are implicitly nonprivate in GLSL
571 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500572 flags.subgroupcoherent ||
573 flags.workgroupcoherent ||
574 flags.queuefamilycoherent ||
575 flags.devicecoherent ||
576 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 flags.volatil = type.getQualifier().volatil;
578 flags.isImage = type.getBasicType() == glslang::EbtSampler;
579 return flags;
580}
581
582spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
583{
584 spv::Scope scope;
585 if (coherentFlags.coherent) {
586 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
587 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
588 } else if (coherentFlags.devicecoherent) {
589 scope = spv::ScopeDevice;
590 } else if (coherentFlags.queuefamilycoherent) {
591 scope = spv::ScopeQueueFamilyKHR;
592 } else if (coherentFlags.workgroupcoherent) {
593 scope = spv::ScopeWorkgroup;
594 } else if (coherentFlags.subgroupcoherent) {
595 scope = spv::ScopeSubgroup;
596 } else {
597 scope = spv::ScopeMax;
598 }
599 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
600 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
601 }
602 return scope;
603}
604
David Netoa901ffe2016-06-08 14:11:40 +0100605// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
606// associated capabilities when required. For some built-in variables, a capability
607// is generated only when using the variable in an executable instruction, but not when
608// just declaring a struct member variable with it. This is true for PointSize,
609// ClipDistance, and CullDistance.
610spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600611{
612 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700613 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600614 // Defer adding the capability until the built-in is actually used.
615 if (! memberDeclaration) {
616 switch (glslangIntermediate->getStage()) {
617 case EShLangGeometry:
618 builder.addCapability(spv::CapabilityGeometryPointSize);
619 break;
620 case EShLangTessControl:
621 case EShLangTessEvaluation:
622 builder.addCapability(spv::CapabilityTessellationPointSize);
623 break;
624 default:
625 break;
626 }
John Kessenich92187592016-02-01 13:45:25 -0700627 }
628 return spv::BuiltInPointSize;
629
John Kessenichebb50532016-05-16 19:22:05 -0600630 // These *Distance capabilities logically belong here, but if the member is declared and
631 // then never used, consumers of SPIR-V prefer the capability not be declared.
632 // They are now generated when used, rather than here when declared.
633 // Potentially, the specification should be more clear what the minimum
634 // use needed is to trigger the capability.
635 //
John Kessenich92187592016-02-01 13:45:25 -0700636 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100637 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800638 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700639 return spv::BuiltInClipDistance;
640
641 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100642 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800643 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700644 return spv::BuiltInCullDistance;
645
646 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600647 builder.addCapability(spv::CapabilityMultiViewport);
648 if (glslangIntermediate->getStage() == EShLangVertex ||
649 glslangIntermediate->getStage() == EShLangTessControl ||
650 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800651
John Kessenichba6a3c22017-09-13 13:22:50 -0600652 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
653 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800654 }
John Kessenich92187592016-02-01 13:45:25 -0700655 return spv::BuiltInViewportIndex;
656
John Kessenich5e801132016-02-15 11:09:46 -0700657 case glslang::EbvSampleId:
658 builder.addCapability(spv::CapabilitySampleRateShading);
659 return spv::BuiltInSampleId;
660
661 case glslang::EbvSamplePosition:
662 builder.addCapability(spv::CapabilitySampleRateShading);
663 return spv::BuiltInSamplePosition;
664
665 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700666 return spv::BuiltInSampleMask;
667
John Kessenich78a45572016-07-08 14:05:15 -0600668 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700669#ifdef NV_EXTENSIONS
670 if (glslangIntermediate->getStage() == EShLangMeshNV) {
671 return spv::BuiltInLayer;
672 }
673#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600674 builder.addCapability(spv::CapabilityGeometry);
675 if (glslangIntermediate->getStage() == EShLangVertex ||
676 glslangIntermediate->getStage() == EShLangTessControl ||
677 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800678
John Kessenichba6a3c22017-09-13 13:22:50 -0600679 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
680 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800681 }
John Kessenich78a45572016-07-08 14:05:15 -0600682 return spv::BuiltInLayer;
683
John Kessenich140f3df2015-06-26 16:58:36 -0600684 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600685 case glslang::EbvVertexId: return spv::BuiltInVertexId;
686 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700687 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
688 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInBaseVertex;
694
John Kessenichda581a22015-10-14 14:10:30 -0600695 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700696 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800697 builder.addCapability(spv::CapabilityDrawParameters);
698 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200699
John Kessenichda581a22015-10-14 14:10:30 -0600700 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700701 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800702 builder.addCapability(spv::CapabilityDrawParameters);
703 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200704
705 case glslang::EbvPrimitiveId:
706 if (glslangIntermediate->getStage() == EShLangFragment)
707 builder.addCapability(spv::CapabilityGeometry);
708 return spv::BuiltInPrimitiveId;
709
Rex Xu37cdcee2017-06-29 17:46:34 +0800710 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800711 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
712 builder.addCapability(spv::CapabilityStencilExportEXT);
713 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800714
John Kessenich140f3df2015-06-26 16:58:36 -0600715 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600716 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
717 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
718 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
719 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
720 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
721 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
722 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600723 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
724 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
725 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
726 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
727 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
728 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
729 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
730 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupSize;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupLocalInvocationId;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupEqMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupGeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupGtMaskKHR;
756
Rex Xu574ab042016-04-14 16:53:07 +0800757 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800758 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
759 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
760 return spv::BuiltInSubgroupLeMaskKHR;
761
Rex Xu574ab042016-04-14 16:53:07 +0800762 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800763 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
764 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
765 return spv::BuiltInSubgroupLtMaskKHR;
766
John Kessenich66011cb2018-03-06 16:12:04 -0700767 case glslang::EbvNumSubgroups:
768 builder.addCapability(spv::CapabilityGroupNonUniform);
769 return spv::BuiltInNumSubgroups;
770
771 case glslang::EbvSubgroupID:
772 builder.addCapability(spv::CapabilityGroupNonUniform);
773 return spv::BuiltInSubgroupId;
774
775 case glslang::EbvSubgroupSize2:
776 builder.addCapability(spv::CapabilityGroupNonUniform);
777 return spv::BuiltInSubgroupSize;
778
779 case glslang::EbvSubgroupInvocation2:
780 builder.addCapability(spv::CapabilityGroupNonUniform);
781 return spv::BuiltInSubgroupLocalInvocationId;
782
783 case glslang::EbvSubgroupEqMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupEqMask;
787
788 case glslang::EbvSubgroupGeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupGeMask;
792
793 case glslang::EbvSubgroupGtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupGtMask;
797
798 case glslang::EbvSubgroupLeMask2:
799 builder.addCapability(spv::CapabilityGroupNonUniform);
800 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
801 return spv::BuiltInSubgroupLeMask;
802
803 case glslang::EbvSubgroupLtMask2:
804 builder.addCapability(spv::CapabilityGroupNonUniform);
805 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
806 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800807#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800808 case glslang::EbvBaryCoordNoPersp:
809 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
810 return spv::BuiltInBaryCoordNoPerspAMD;
811
812 case glslang::EbvBaryCoordNoPerspCentroid:
813 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
814 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
815
816 case glslang::EbvBaryCoordNoPerspSample:
817 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
818 return spv::BuiltInBaryCoordNoPerspSampleAMD;
819
820 case glslang::EbvBaryCoordSmooth:
821 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
822 return spv::BuiltInBaryCoordSmoothAMD;
823
824 case glslang::EbvBaryCoordSmoothCentroid:
825 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
826 return spv::BuiltInBaryCoordSmoothCentroidAMD;
827
828 case glslang::EbvBaryCoordSmoothSample:
829 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
830 return spv::BuiltInBaryCoordSmoothSampleAMD;
831
832 case glslang::EbvBaryCoordPullModel:
833 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
834 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800835#endif
chaoc771d89f2017-01-13 01:10:53 -0800836
John Kessenich6c8aaac2017-02-27 01:20:51 -0700837 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700838 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700839 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700840 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700841
842 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700843 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700844 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700845 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700846
Daniel Koch5154db52018-11-26 10:01:58 -0500847 case glslang::EbvFragSizeEXT:
848 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
849 builder.addCapability(spv::CapabilityFragmentDensityEXT);
850 return spv::BuiltInFragSizeEXT;
851
852 case glslang::EbvFragInvocationCountEXT:
853 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
854 builder.addCapability(spv::CapabilityFragmentDensityEXT);
855 return spv::BuiltInFragInvocationCountEXT;
856
chaoc771d89f2017-01-13 01:10:53 -0800857#ifdef NV_EXTENSIONS
858 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800859 if (!memberDeclaration) {
860 builder.addExtension(spv::E_SPV_NV_viewport_array2);
861 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
862 }
chaoc771d89f2017-01-13 01:10:53 -0800863 return spv::BuiltInViewportMaskNV;
864 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800865 if (!memberDeclaration) {
866 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
867 builder.addCapability(spv::CapabilityShaderStereoViewNV);
868 }
chaoc771d89f2017-01-13 01:10:53 -0800869 return spv::BuiltInSecondaryPositionNV;
870 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800871 if (!memberDeclaration) {
872 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
873 builder.addCapability(spv::CapabilityShaderStereoViewNV);
874 }
chaoc771d89f2017-01-13 01:10:53 -0800875 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800876 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800877 if (!memberDeclaration) {
878 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
879 builder.addCapability(spv::CapabilityPerViewAttributesNV);
880 }
chaocdf3956c2017-02-14 14:52:34 -0800881 return spv::BuiltInPositionPerViewNV;
882 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800883 if (!memberDeclaration) {
884 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
885 builder.addCapability(spv::CapabilityPerViewAttributesNV);
886 }
chaocdf3956c2017-02-14 14:52:34 -0800887 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700888 case glslang::EbvFragFullyCoveredNV:
889 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
890 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
891 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700892 case glslang::EbvFragmentSizeNV:
893 builder.addExtension(spv::E_SPV_NV_shading_rate);
894 builder.addCapability(spv::CapabilityShadingRateNV);
895 return spv::BuiltInFragmentSizeNV;
896 case glslang::EbvInvocationsPerPixelNV:
897 builder.addExtension(spv::E_SPV_NV_shading_rate);
898 builder.addCapability(spv::CapabilityShadingRateNV);
899 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900
901 // raytracing
902 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700918 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700919 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700920 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700921 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700922 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700923 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700924 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700925 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700926 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700927 return spv::BuiltInWorldToObjectNV;
928 case glslang::EbvIncomingRayFlagsNV:
929 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700930 case glslang::EbvBaryCoordNV:
931 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
932 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
933 return spv::BuiltInBaryCoordNV;
934 case glslang::EbvBaryCoordNoPerspNV:
935 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
936 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
937 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700938 case glslang::EbvTaskCountNV:
939 return spv::BuiltInTaskCountNV;
940 case glslang::EbvPrimitiveCountNV:
941 return spv::BuiltInPrimitiveCountNV;
942 case glslang::EbvPrimitiveIndicesNV:
943 return spv::BuiltInPrimitiveIndicesNV;
944 case glslang::EbvClipDistancePerViewNV:
945 return spv::BuiltInClipDistancePerViewNV;
946 case glslang::EbvCullDistancePerViewNV:
947 return spv::BuiltInCullDistancePerViewNV;
948 case glslang::EbvLayerPerViewNV:
949 return spv::BuiltInLayerPerViewNV;
950 case glslang::EbvMeshViewCountNV:
951 return spv::BuiltInMeshViewCountNV;
952 case glslang::EbvMeshViewIndicesNV:
953 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800954#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800955 default:
956 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600957 }
958}
959
Rex Xufc618912015-09-09 16:42:49 +0800960// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700961spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800962{
963 assert(type.getBasicType() == glslang::EbtSampler);
964
John Kessenich5d0fa972016-02-15 11:57:00 -0700965 // Check for capabilities
966 switch (type.getQualifier().layoutFormat) {
967 case glslang::ElfRg32f:
968 case glslang::ElfRg16f:
969 case glslang::ElfR11fG11fB10f:
970 case glslang::ElfR16f:
971 case glslang::ElfRgba16:
972 case glslang::ElfRgb10A2:
973 case glslang::ElfRg16:
974 case glslang::ElfRg8:
975 case glslang::ElfR16:
976 case glslang::ElfR8:
977 case glslang::ElfRgba16Snorm:
978 case glslang::ElfRg16Snorm:
979 case glslang::ElfRg8Snorm:
980 case glslang::ElfR16Snorm:
981 case glslang::ElfR8Snorm:
982
983 case glslang::ElfRg32i:
984 case glslang::ElfRg16i:
985 case glslang::ElfRg8i:
986 case glslang::ElfR16i:
987 case glslang::ElfR8i:
988
989 case glslang::ElfRgb10a2ui:
990 case glslang::ElfRg32ui:
991 case glslang::ElfRg16ui:
992 case glslang::ElfRg8ui:
993 case glslang::ElfR16ui:
994 case glslang::ElfR8ui:
995 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
996 break;
997
998 default:
999 break;
1000 }
1001
1002 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001003 switch (type.getQualifier().layoutFormat) {
1004 case glslang::ElfNone: return spv::ImageFormatUnknown;
1005 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1006 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1007 case glslang::ElfR32f: return spv::ImageFormatR32f;
1008 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1009 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1010 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1011 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1012 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1013 case glslang::ElfR16f: return spv::ImageFormatR16f;
1014 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1015 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1016 case glslang::ElfRg16: return spv::ImageFormatRg16;
1017 case glslang::ElfRg8: return spv::ImageFormatRg8;
1018 case glslang::ElfR16: return spv::ImageFormatR16;
1019 case glslang::ElfR8: return spv::ImageFormatR8;
1020 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1021 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1022 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1023 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1024 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1025 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1026 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1027 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1028 case glslang::ElfR32i: return spv::ImageFormatR32i;
1029 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1030 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1031 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1032 case glslang::ElfR16i: return spv::ImageFormatR16i;
1033 case glslang::ElfR8i: return spv::ImageFormatR8i;
1034 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1035 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1036 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1037 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1038 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1039 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1040 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1041 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1042 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1043 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001044 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001045 }
1046}
1047
John Kesseniche18fd202018-01-30 11:01:39 -07001048spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001049{
John Kesseniche18fd202018-01-30 11:01:39 -07001050 if (selectionNode.getFlatten())
1051 return spv::SelectionControlFlattenMask;
1052 if (selectionNode.getDontFlatten())
1053 return spv::SelectionControlDontFlattenMask;
1054 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001055}
1056
John Kesseniche18fd202018-01-30 11:01:39 -07001057spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001058{
John Kesseniche18fd202018-01-30 11:01:39 -07001059 if (switchNode.getFlatten())
1060 return spv::SelectionControlFlattenMask;
1061 if (switchNode.getDontFlatten())
1062 return spv::SelectionControlDontFlattenMask;
1063 return spv::SelectionControlMaskNone;
1064}
1065
John Kessenicha2858d92018-01-31 08:11:18 -07001066// return a non-0 dependency if the dependency argument must be set
1067spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1068 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001069{
1070 spv::LoopControlMask control = spv::LoopControlMaskNone;
1071
1072 if (loopNode.getDontUnroll())
1073 control = control | spv::LoopControlDontUnrollMask;
1074 if (loopNode.getUnroll())
1075 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001076 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001077 control = control | spv::LoopControlDependencyInfiniteMask;
1078 else if (loopNode.getLoopDependency() > 0) {
1079 control = control | spv::LoopControlDependencyLengthMask;
1080 dependencyLength = loopNode.getLoopDependency();
1081 }
John Kesseniche18fd202018-01-30 11:01:39 -07001082
1083 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001084}
1085
John Kessenicha5c5fb62017-05-05 05:09:58 -06001086// Translate glslang type to SPIR-V storage class.
1087spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1088{
1089 if (type.getQualifier().isPipeInput())
1090 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001091 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001092 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001093
1094 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1095 type.getQualifier().storage == glslang::EvqUniform) {
1096 if (type.getBasicType() == glslang::EbtAtomicUint)
1097 return spv::StorageClassAtomicCounter;
1098 if (type.containsOpaque())
1099 return spv::StorageClassUniformConstant;
1100 }
1101
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001102#ifdef NV_EXTENSIONS
1103 if (type.getQualifier().isUniformOrBuffer() &&
1104 type.getQualifier().layoutShaderRecordNV) {
1105 return spv::StorageClassShaderRecordBufferNV;
1106 }
1107#endif
1108
John Kessenichbed4e4f2017-09-08 02:38:07 -06001109 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001110 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001111 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001112 }
1113
1114 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001115 if (type.getQualifier().layoutPushConstant)
1116 return spv::StorageClassPushConstant;
1117 if (type.getBasicType() == glslang::EbtBlock)
1118 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001119 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001120 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001121
1122 switch (type.getQualifier().storage) {
1123 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1124 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1125 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1126 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001127#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001128 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1129 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1130 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1131 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1132 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001133#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001134 default:
1135 assert(0);
1136 break;
1137 }
1138
1139 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001140}
1141
John Kessenich5611c6d2018-04-05 11:25:02 -06001142// Add capabilities pertaining to how an array is indexed.
1143void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1144 const glslang::TType& indexType)
1145{
1146 if (indexType.getQualifier().isNonUniform()) {
1147 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001148 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001149 if (baseType.getBasicType() == glslang::EbtSampler) {
1150 if (baseType.getQualifier().hasAttachment())
1151 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1152 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1153 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1154 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1155 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1156 else if (baseType.isImage())
1157 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1158 else if (baseType.isTexture())
1159 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1160 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1161 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1162 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1163 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1164 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1165 }
1166 } else {
1167 // assume a dynamically uniform index
1168 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001169 if (baseType.getQualifier().hasAttachment()) {
1170 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001171 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001172 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1173 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001174 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001175 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1176 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001177 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001178 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001179 }
1180 }
1181}
1182
qining25262b32016-05-06 17:25:16 -04001183// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001184// descriptor set.
1185bool IsDescriptorResource(const glslang::TType& type)
1186{
John Kessenichf7497e22016-03-08 21:36:22 -07001187 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001188 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001189 return type.getQualifier().isUniformOrBuffer() &&
1190#ifdef NV_EXTENSIONS
1191 ! type.getQualifier().layoutShaderRecordNV &&
1192#endif
1193 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001194
1195 // non block...
1196 // basically samplerXXX/subpass/sampler/texture are all included
1197 // if they are the global-scope-class, not the function parameter
1198 // (or local, if they ever exist) class.
1199 if (type.getBasicType() == glslang::EbtSampler)
1200 return type.getQualifier().isUniformOrBuffer();
1201
1202 // None of the above.
1203 return false;
1204}
1205
John Kesseniche0b6cad2015-12-24 10:30:13 -07001206void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1207{
1208 if (child.layoutMatrix == glslang::ElmNone)
1209 child.layoutMatrix = parent.layoutMatrix;
1210
1211 if (parent.invariant)
1212 child.invariant = true;
1213 if (parent.nopersp)
1214 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001215#ifdef AMD_EXTENSIONS
1216 if (parent.explicitInterp)
1217 child.explicitInterp = true;
1218#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001219 if (parent.flat)
1220 child.flat = true;
1221 if (parent.centroid)
1222 child.centroid = true;
1223 if (parent.patch)
1224 child.patch = true;
1225 if (parent.sample)
1226 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001227 if (parent.coherent)
1228 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001229 if (parent.devicecoherent)
1230 child.devicecoherent = true;
1231 if (parent.queuefamilycoherent)
1232 child.queuefamilycoherent = true;
1233 if (parent.workgroupcoherent)
1234 child.workgroupcoherent = true;
1235 if (parent.subgroupcoherent)
1236 child.subgroupcoherent = true;
1237 if (parent.nonprivate)
1238 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001239 if (parent.volatil)
1240 child.volatil = true;
1241 if (parent.restrict)
1242 child.restrict = true;
1243 if (parent.readonly)
1244 child.readonly = true;
1245 if (parent.writeonly)
1246 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001247#ifdef NV_EXTENSIONS
1248 if (parent.perPrimitiveNV)
1249 child.perPrimitiveNV = true;
1250 if (parent.perViewNV)
1251 child.perViewNV = true;
1252 if (parent.perTaskNV)
1253 child.perTaskNV = true;
1254#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001255}
1256
John Kessenichf2b7f332016-09-01 17:05:23 -06001257bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001258{
John Kessenich7b9fa252016-01-21 18:56:57 -07001259 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001260 // - struct members might inherit from a struct declaration
1261 // (note that non-block structs don't explicitly inherit,
1262 // only implicitly, meaning no decoration involved)
1263 // - affect decorations on the struct members
1264 // (note smooth does not, and expecting something like volatile
1265 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001266 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001267 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001268}
1269
John Kessenich140f3df2015-06-26 16:58:36 -06001270//
1271// Implement the TGlslangToSpvTraverser class.
1272//
1273
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001274TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001275 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1276 : TIntermTraverser(true, false, true),
1277 options(options),
1278 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001279 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001280 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001281 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001282 glslangIntermediate(glslangIntermediate)
1283{
1284 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1285
1286 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001287 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1288 glslangIntermediate->getVersion());
1289
John Kessenich121853f2017-05-31 17:11:16 -06001290 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001291 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001292 builder.setSourceFile(glslangIntermediate->getSourceFile());
1293
1294 // Set the source shader's text. If for SPV version 1.0, include
1295 // a preamble in comments stating the OpModuleProcessed instructions.
1296 // Otherwise, emit those as actual instructions.
1297 std::string text;
1298 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1299 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001300 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001301 text.append("// OpModuleProcessed ");
1302 text.append(processes[p]);
1303 text.append("\n");
1304 } else
1305 builder.addModuleProcessed(processes[p]);
1306 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001307 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001308 text.append("#line 1\n");
1309 text.append(glslangIntermediate->getSourceText());
1310 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001311 // Pass name and text for all included files
1312 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1313 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1314 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001315 }
John Kessenich140f3df2015-06-26 16:58:36 -06001316 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001317
1318 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1319 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1320
1321 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1322 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1323 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1324 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1325 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001326 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001327 memoryModel = spv::MemoryModelVulkanKHR;
1328 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001329 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001331 builder.setMemoryModel(addressingModel, memoryModel);
1332
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001333 if (glslangIntermediate->usingVariablePointers()) {
1334 builder.addCapability(spv::CapabilityVariablePointers);
1335 }
1336
John Kessenicheee9d532016-09-19 18:09:30 -06001337 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1338 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001339
1340 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001341 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1342 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001343 builder.addSourceExtension(it->c_str());
1344
1345 // Add the top-level modes for this shader.
1346
John Kessenich92187592016-02-01 13:45:25 -07001347 if (glslangIntermediate->getXfbMode()) {
1348 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001349 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001350 }
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 unsigned int mode;
1353 switch (glslangIntermediate->getStage()) {
1354 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001355 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001356 break;
1357
steve-lunarge7412492017-03-23 11:56:07 -06001358 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001359 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001360 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001361
steve-lunarge7412492017-03-23 11:56:07 -06001362 glslang::TLayoutGeometry primitive;
1363
1364 if (glslangIntermediate->getStage() == EShLangTessControl) {
1365 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1366 primitive = glslangIntermediate->getOutputPrimitive();
1367 } else {
1368 primitive = glslangIntermediate->getInputPrimitive();
1369 }
1370
1371 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001372 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1373 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1374 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001375 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001376 }
John Kessenich4016e382016-07-15 11:53:56 -06001377 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001378 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1379
John Kesseniche6903322015-10-13 16:29:02 -06001380 switch (glslangIntermediate->getVertexSpacing()) {
1381 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1382 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1383 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001384 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001385 }
John Kessenich4016e382016-07-15 11:53:56 -06001386 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001387 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1388
1389 switch (glslangIntermediate->getVertexOrder()) {
1390 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1391 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001392 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001393 }
John Kessenich4016e382016-07-15 11:53:56 -06001394 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001395 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1396
1397 if (glslangIntermediate->getPointMode())
1398 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 break;
1400
1401 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001402 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001403 switch (glslangIntermediate->getInputPrimitive()) {
1404 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1405 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1406 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001407 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001408 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001409 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001410 }
John Kessenich4016e382016-07-15 11:53:56 -06001411 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001412 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001413
John Kessenich140f3df2015-06-26 16:58:36 -06001414 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1415
1416 switch (glslangIntermediate->getOutputPrimitive()) {
1417 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1418 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1419 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001420 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001421 }
John Kessenich4016e382016-07-15 11:53:56 -06001422 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001423 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1424 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1425 break;
1426
1427 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001428 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 if (glslangIntermediate->getPixelCenterInteger())
1430 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001431
John Kessenich140f3df2015-06-26 16:58:36 -06001432 if (glslangIntermediate->getOriginUpperLeft())
1433 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001434 else
1435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001436
1437 if (glslangIntermediate->getEarlyFragmentTests())
1438 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1439
chaocc1204522017-06-30 17:14:30 -07001440 if (glslangIntermediate->getPostDepthCoverage()) {
1441 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1443 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1444 }
1445
John Kesseniche6903322015-10-13 16:29:02 -06001446 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001447 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1448 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001449 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001450 }
John Kessenich4016e382016-07-15 11:53:56 -06001451 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001452 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1453
1454 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1455 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001456 break;
1457
1458 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001459 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001460 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1461 glslangIntermediate->getLocalSize(1),
1462 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001463#ifdef NV_EXTENSIONS
1464 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1465 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1466 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1467 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1468 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1469 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1471 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1472 }
1473#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001474 break;
1475
Chao Chen3c366992018-09-19 11:41:59 -07001476#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001477 case EShLangRayGenNV:
1478 case EShLangIntersectNV:
1479 case EShLangAnyHitNV:
1480 case EShLangClosestHitNV:
1481 case EShLangMissNV:
1482 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001483 builder.addCapability(spv::CapabilityRayTracingNV);
1484 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001485 break;
Chao Chen3c366992018-09-19 11:41:59 -07001486 case EShLangTaskNV:
1487 case EShLangMeshNV:
1488 builder.addCapability(spv::CapabilityMeshShadingNV);
1489 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1490 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1491 glslangIntermediate->getLocalSize(1),
1492 glslangIntermediate->getLocalSize(2));
1493 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1494 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1495 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1496
1497 switch (glslangIntermediate->getOutputPrimitive()) {
1498 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1499 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1500 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1501 default: mode = spv::ExecutionModeMax; break;
1502 }
1503 if (mode != spv::ExecutionModeMax)
1504 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1505 }
1506 break;
1507#endif
1508
John Kessenich140f3df2015-06-26 16:58:36 -06001509 default:
1510 break;
1511 }
John Kessenich140f3df2015-06-26 16:58:36 -06001512}
1513
John Kessenichfca82622016-11-26 13:23:20 -07001514// Finish creating SPV, after the traversal is complete.
1515void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001516{
John Kessenichf04c51b2018-08-03 15:56:12 -06001517 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001518 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001519 builder.setBuildPoint(shaderEntry->getLastBlock());
1520 builder.leaveFunction();
1521 }
1522
John Kessenich7ba63412015-12-20 17:37:07 -07001523 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001524 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1525 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001526
John Kessenichf04c51b2018-08-03 15:56:12 -06001527 // Add capabilities, extensions, remove unneeded decorations, etc.,
1528 // based on the resulting SPIR-V.
1529 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001530}
1531
John Kessenichfca82622016-11-26 13:23:20 -07001532// Write the SPV into 'out'.
1533void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001534{
John Kessenichfca82622016-11-26 13:23:20 -07001535 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001536}
1537
1538//
1539// Implement the traversal functions.
1540//
1541// Return true from interior nodes to have the external traversal
1542// continue on to children. Return false if children were
1543// already processed.
1544//
1545
1546//
qining25262b32016-05-06 17:25:16 -04001547// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001548// - uniform/input reads
1549// - output writes
1550// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1551// - something simple that degenerates into the last bullet
1552//
1553void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1554{
qining75d1d802016-04-06 14:42:01 -04001555 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1556 if (symbol->getType().getQualifier().isSpecConstant())
1557 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1558
John Kessenich140f3df2015-06-26 16:58:36 -06001559 // getSymbolId() will set up all the IO decorations on the first call.
1560 // Formal function parameters were mapped during makeFunctions().
1561 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001562
1563 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1564 if (builder.isPointer(id)) {
1565 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001566 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1567 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1568 iOSet.insert(id);
1569 }
John Kessenich7ba63412015-12-20 17:37:07 -07001570 }
1571
1572 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001573 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001574 // Prepare to generate code for the access
1575
1576 // L-value chains will be computed left to right. We're on the symbol now,
1577 // which is the left-most part of the access chain, so now is "clear" time,
1578 // followed by setting the base.
1579 builder.clearAccessChain();
1580
1581 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001582 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001583 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001584 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001585 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001586 // These are also pure R-values.
1587 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001588 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001589 builder.setAccessChainRValue(id);
1590 else
1591 builder.setAccessChainLValue(id);
1592 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001593
1594 // Process linkage-only nodes for any special additional interface work.
1595 if (linkageOnly) {
1596 if (glslangIntermediate->getHlslFunctionality1()) {
1597 // Map implicit counter buffers to their originating buffers, which should have been
1598 // seen by now, given earlier pruning of unused counters, and preservation of order
1599 // of declaration.
1600 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1601 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1602 // Save possible originating buffers for counter buffers, keyed by
1603 // making the potential counter-buffer name.
1604 std::string keyName = symbol->getName().c_str();
1605 keyName = glslangIntermediate->addCounterBufferName(keyName);
1606 counterOriginator[keyName] = symbol;
1607 } else {
1608 // Handle a counter buffer, by finding the saved originating buffer.
1609 std::string keyName = symbol->getName().c_str();
1610 auto it = counterOriginator.find(keyName);
1611 if (it != counterOriginator.end()) {
1612 id = getSymbolId(it->second);
1613 if (id != spv::NoResult) {
1614 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001615 if (counterId != spv::NoResult) {
1616 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001617 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001618 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001619 }
1620 }
1621 }
1622 }
1623 }
1624 }
John Kessenich140f3df2015-06-26 16:58:36 -06001625}
1626
1627bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1628{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001629 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001630
qining40887662016-04-03 22:20:42 -04001631 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1632 if (node->getType().getQualifier().isSpecConstant())
1633 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1634
John Kessenich140f3df2015-06-26 16:58:36 -06001635 // First, handle special cases
1636 switch (node->getOp()) {
1637 case glslang::EOpAssign:
1638 case glslang::EOpAddAssign:
1639 case glslang::EOpSubAssign:
1640 case glslang::EOpMulAssign:
1641 case glslang::EOpVectorTimesMatrixAssign:
1642 case glslang::EOpVectorTimesScalarAssign:
1643 case glslang::EOpMatrixTimesScalarAssign:
1644 case glslang::EOpMatrixTimesMatrixAssign:
1645 case glslang::EOpDivAssign:
1646 case glslang::EOpModAssign:
1647 case glslang::EOpAndAssign:
1648 case glslang::EOpInclusiveOrAssign:
1649 case glslang::EOpExclusiveOrAssign:
1650 case glslang::EOpLeftShiftAssign:
1651 case glslang::EOpRightShiftAssign:
1652 // A bin-op assign "a += b" means the same thing as "a = a + b"
1653 // where a is evaluated before b. For a simple assignment, GLSL
1654 // says to evaluate the left before the right. So, always, left
1655 // node then right node.
1656 {
1657 // get the left l-value, save it away
1658 builder.clearAccessChain();
1659 node->getLeft()->traverse(this);
1660 spv::Builder::AccessChain lValue = builder.getAccessChain();
1661
1662 // evaluate the right
1663 builder.clearAccessChain();
1664 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001665 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001666
1667 if (node->getOp() != glslang::EOpAssign) {
1668 // the left is also an r-value
1669 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001670 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001671
1672 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001673 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001674 TranslateNoContractionDecoration(node->getType().getQualifier()),
1675 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001676 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001677 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1678 node->getType().getBasicType());
1679
1680 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001681 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001682 }
1683
1684 // store the result
1685 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001686 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001687
1688 // assignments are expressions having an rValue after they are evaluated...
1689 builder.clearAccessChain();
1690 builder.setAccessChainRValue(rValue);
1691 }
1692 return false;
1693 case glslang::EOpIndexDirect:
1694 case glslang::EOpIndexDirectStruct:
1695 {
1696 // Get the left part of the access chain.
1697 node->getLeft()->traverse(this);
1698
1699 // Add the next element in the chain
1700
David Netoa901ffe2016-06-08 14:11:40 +01001701 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001702 if (! node->getLeft()->getType().isArray() &&
1703 node->getLeft()->getType().isVector() &&
1704 node->getOp() == glslang::EOpIndexDirect) {
1705 // This is essentially a hard-coded vector swizzle of size 1,
1706 // so short circuit the access-chain stuff with a swizzle.
1707 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001708 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001709 int dummySize;
1710 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1711 TranslateCoherent(node->getLeft()->getType()),
1712 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001713 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001714
1715 // Load through a block reference is performed with a dot operator that
1716 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1717 // do a load and reset the access chain.
1718 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1719 !node->getLeft()->getType().isArray() &&
1720 node->getOp() == glslang::EOpIndexDirectStruct)
1721 {
1722 spv::Id left = accessChainLoad(node->getLeft()->getType());
1723 builder.clearAccessChain();
1724 builder.setAccessChainLValue(left);
1725 }
1726
David Netoa901ffe2016-06-08 14:11:40 +01001727 int spvIndex = glslangIndex;
1728 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1729 node->getOp() == glslang::EOpIndexDirectStruct)
1730 {
1731 // This may be, e.g., an anonymous block-member selection, which generally need
1732 // index remapping due to hidden members in anonymous blocks.
1733 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1734 assert(remapper.size() > 0);
1735 spvIndex = remapper[glslangIndex];
1736 }
John Kessenichebb50532016-05-16 19:22:05 -06001737
David Netoa901ffe2016-06-08 14:11:40 +01001738 // normal case for indexing array or structure or block
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001739 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001740
1741 // Add capabilities here for accessing PointSize and clip/cull distance.
1742 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001743 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001744 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001745 }
1746 }
1747 return false;
1748 case glslang::EOpIndexIndirect:
1749 {
1750 // Structure or array or vector indirection.
1751 // Will use native SPIR-V access-chain for struct and array indirection;
1752 // matrices are arrays of vectors, so will also work for a matrix.
1753 // Will use the access chain's 'component' for variable index into a vector.
1754
1755 // This adapter is building access chains left to right.
1756 // Set up the access chain to the left.
1757 node->getLeft()->traverse(this);
1758
1759 // save it so that computing the right side doesn't trash it
1760 spv::Builder::AccessChain partial = builder.getAccessChain();
1761
1762 // compute the next index in the chain
1763 builder.clearAccessChain();
1764 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001765 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001766
John Kessenich5611c6d2018-04-05 11:25:02 -06001767 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1768
John Kessenich140f3df2015-06-26 16:58:36 -06001769 // restore the saved access chain
1770 builder.setAccessChain(partial);
1771
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001772 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1773 int dummySize;
1774 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1775 TranslateCoherent(node->getLeft()->getType()),
1776 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1777 } else
1778 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001779 }
1780 return false;
1781 case glslang::EOpVectorSwizzle:
1782 {
1783 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001784 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001785 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001786 int dummySize;
1787 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1788 TranslateCoherent(node->getLeft()->getType()),
1789 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001790 }
1791 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001792 case glslang::EOpMatrixSwizzle:
1793 logger->missingFunctionality("matrix swizzle");
1794 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001795 case glslang::EOpLogicalOr:
1796 case glslang::EOpLogicalAnd:
1797 {
1798
1799 // These may require short circuiting, but can sometimes be done as straight
1800 // binary operations. The right operand must be short circuited if it has
1801 // side effects, and should probably be if it is complex.
1802 if (isTrivial(node->getRight()->getAsTyped()))
1803 break; // handle below as a normal binary operation
1804 // otherwise, we need to do dynamic short circuiting on the right operand
1805 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1806 builder.clearAccessChain();
1807 builder.setAccessChainRValue(result);
1808 }
1809 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001810 default:
1811 break;
1812 }
1813
1814 // Assume generic binary op...
1815
John Kessenich32cfd492016-02-02 12:37:46 -07001816 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001817 builder.clearAccessChain();
1818 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001819 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001820
John Kessenich32cfd492016-02-02 12:37:46 -07001821 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001822 builder.clearAccessChain();
1823 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001824 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001825
John Kessenich32cfd492016-02-02 12:37:46 -07001826 // get result
John Kessenichead86222018-03-28 18:01:20 -06001827 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001828 TranslateNoContractionDecoration(node->getType().getQualifier()),
1829 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001830 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001831 convertGlslangToSpvType(node->getType()), left, right,
1832 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001833
John Kessenich50e57562015-12-21 21:21:11 -07001834 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001835 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001836 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001837 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001838 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001839 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001840 return false;
1841 }
John Kessenich140f3df2015-06-26 16:58:36 -06001842}
1843
1844bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1845{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001846 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001847
qining40887662016-04-03 22:20:42 -04001848 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1849 if (node->getType().getQualifier().isSpecConstant())
1850 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1851
John Kessenichfc51d282015-08-19 13:34:18 -06001852 spv::Id result = spv::NoResult;
1853
1854 // try texturing first
1855 result = createImageTextureFunctionCall(node);
1856 if (result != spv::NoResult) {
1857 builder.clearAccessChain();
1858 builder.setAccessChainRValue(result);
1859
1860 return false; // done with this node
1861 }
1862
1863 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001864
1865 if (node->getOp() == glslang::EOpArrayLength) {
1866 // Quite special; won't want to evaluate the operand.
1867
John Kessenich5611c6d2018-04-05 11:25:02 -06001868 // Currently, the front-end does not allow .length() on an array until it is sized,
1869 // except for the last block membeor of an SSBO.
1870 // TODO: If this changes, link-time sized arrays might show up here, and need their
1871 // size extracted.
1872
John Kessenichc9a80832015-09-12 12:17:44 -06001873 // Normal .length() would have been constant folded by the front-end.
1874 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001875 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001876
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001877 spv::Id length;
1878 if (node->getOperand()->getType().isCoopMat()) {
1879 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1880
1881 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1882 assert(builder.isCooperativeMatrixType(typeId));
1883
1884 length = builder.createCooperativeMatrixLength(typeId);
1885 } else {
1886 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1887 block->traverse(this);
1888 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1889 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1890 }
John Kessenichc9a80832015-09-12 12:17:44 -06001891
John Kessenich8c869672018-11-28 07:01:37 -07001892 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1893 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1894 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001895 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1896 if (builder.isInSpecConstCodeGenMode()) {
1897 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1898 } else {
1899 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1900 }
1901 }
John Kessenich8c869672018-11-28 07:01:37 -07001902
John Kessenichc9a80832015-09-12 12:17:44 -06001903 builder.clearAccessChain();
1904 builder.setAccessChainRValue(length);
1905
1906 return false;
1907 }
1908
John Kessenichfc51d282015-08-19 13:34:18 -06001909 // Start by evaluating the operand
1910
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 // Does it need a swizzle inversion? If so, evaluation is inverted;
1912 // operate first on the swizzle base, then apply the swizzle.
1913 spv::Id invertedType = spv::NoType;
1914 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1915 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1916 invertedType = getInvertedSwizzleType(*node->getOperand());
1917
John Kessenich140f3df2015-06-26 16:58:36 -06001918 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001919 if (invertedType != spv::NoType)
1920 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1921 else
1922 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001923
Rex Xufc618912015-09-09 16:42:49 +08001924 spv::Id operand = spv::NoResult;
1925
1926 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1927 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001928 node->getOp() == glslang::EOpAtomicCounter ||
1929 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001930 operand = builder.accessChainGetLValue(); // Special case l-value operands
1931 else
John Kessenich32cfd492016-02-02 12:37:46 -07001932 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001933
John Kessenichead86222018-03-28 18:01:20 -06001934 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001935 TranslateNoContractionDecoration(node->getType().getQualifier()),
1936 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001937
1938 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001939 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001940 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001941
1942 // if not, then possibly an operation
1943 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001944 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001945
1946 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001947 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001948 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001949 builder.addDecoration(result, decorations.nonUniform);
1950 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001951
John Kessenich140f3df2015-06-26 16:58:36 -06001952 builder.clearAccessChain();
1953 builder.setAccessChainRValue(result);
1954
1955 return false; // done with this node
1956 }
1957
1958 // it must be a special case, check...
1959 switch (node->getOp()) {
1960 case glslang::EOpPostIncrement:
1961 case glslang::EOpPostDecrement:
1962 case glslang::EOpPreIncrement:
1963 case glslang::EOpPreDecrement:
1964 {
1965 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001966 spv::Id one = 0;
1967 if (node->getBasicType() == glslang::EbtFloat)
1968 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001969 else if (node->getBasicType() == glslang::EbtDouble)
1970 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001971 else if (node->getBasicType() == glslang::EbtFloat16)
1972 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001973 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1974 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001975 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1976 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001977 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1978 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001979 else
1980 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001981 glslang::TOperator op;
1982 if (node->getOp() == glslang::EOpPreIncrement ||
1983 node->getOp() == glslang::EOpPostIncrement)
1984 op = glslang::EOpAdd;
1985 else
1986 op = glslang::EOpSub;
1987
John Kessenichead86222018-03-28 18:01:20 -06001988 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001989 convertGlslangToSpvType(node->getType()), operand, one,
1990 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001991 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001992
1993 // The result of operation is always stored, but conditionally the
1994 // consumed result. The consumed result is always an r-value.
1995 builder.accessChainStore(result);
1996 builder.clearAccessChain();
1997 if (node->getOp() == glslang::EOpPreIncrement ||
1998 node->getOp() == glslang::EOpPreDecrement)
1999 builder.setAccessChainRValue(result);
2000 else
2001 builder.setAccessChainRValue(operand);
2002 }
2003
2004 return false;
2005
2006 case glslang::EOpEmitStreamVertex:
2007 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2008 return false;
2009 case glslang::EOpEndStreamPrimitive:
2010 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2011 return false;
2012
2013 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002014 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002015 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002016 }
John Kessenich140f3df2015-06-26 16:58:36 -06002017}
2018
2019bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2020{
qining27e04a02016-04-14 16:40:20 -04002021 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2022 if (node->getType().getQualifier().isSpecConstant())
2023 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2024
John Kessenichfc51d282015-08-19 13:34:18 -06002025 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002026 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2027 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002028
2029 // try texturing
2030 result = createImageTextureFunctionCall(node);
2031 if (result != spv::NoResult) {
2032 builder.clearAccessChain();
2033 builder.setAccessChainRValue(result);
2034
2035 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002036 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002037#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002038 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002039#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002040 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002041 // "imageStore" is a special case, which has no result
2042 return false;
2043 }
John Kessenichfc51d282015-08-19 13:34:18 -06002044
John Kessenich140f3df2015-06-26 16:58:36 -06002045 glslang::TOperator binOp = glslang::EOpNull;
2046 bool reduceComparison = true;
2047 bool isMatrix = false;
2048 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002049 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002050
2051 assert(node->getOp());
2052
John Kessenichf6640762016-08-01 19:44:00 -06002053 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002054
2055 switch (node->getOp()) {
2056 case glslang::EOpSequence:
2057 {
2058 if (preVisit)
2059 ++sequenceDepth;
2060 else
2061 --sequenceDepth;
2062
2063 if (sequenceDepth == 1) {
2064 // If this is the parent node of all the functions, we want to see them
2065 // early, so all call points have actual SPIR-V functions to reference.
2066 // In all cases, still let the traverser visit the children for us.
2067 makeFunctions(node->getAsAggregate()->getSequence());
2068
John Kessenich6fccb3c2016-09-19 16:01:41 -06002069 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002070 // anything else gets there, so visit out of order, doing them all now.
2071 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2072
John Kessenich6a60c2f2016-12-08 21:01:59 -07002073 // 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 -06002074 // so do them manually.
2075 visitFunctions(node->getAsAggregate()->getSequence());
2076
2077 return false;
2078 }
2079
2080 return true;
2081 }
2082 case glslang::EOpLinkerObjects:
2083 {
2084 if (visit == glslang::EvPreVisit)
2085 linkageOnly = true;
2086 else
2087 linkageOnly = false;
2088
2089 return true;
2090 }
2091 case glslang::EOpComma:
2092 {
2093 // processing from left to right naturally leaves the right-most
2094 // lying around in the access chain
2095 glslang::TIntermSequence& glslangOperands = node->getSequence();
2096 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2097 glslangOperands[i]->traverse(this);
2098
2099 return false;
2100 }
2101 case glslang::EOpFunction:
2102 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002103 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002104 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002105 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002106 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002107 } else {
2108 handleFunctionEntry(node);
2109 }
2110 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002111 if (inEntryPoint)
2112 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002113 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002114 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002115 }
2116
2117 return true;
2118 case glslang::EOpParameters:
2119 // Parameters will have been consumed by EOpFunction processing, but not
2120 // the body, so we still visited the function node's children, making this
2121 // child redundant.
2122 return false;
2123 case glslang::EOpFunctionCall:
2124 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002125 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002126 if (node->isUserDefined())
2127 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002128 // 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 -07002129 if (result) {
2130 builder.clearAccessChain();
2131 builder.setAccessChainRValue(result);
2132 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002133 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002134
2135 return false;
2136 }
2137 case glslang::EOpConstructMat2x2:
2138 case glslang::EOpConstructMat2x3:
2139 case glslang::EOpConstructMat2x4:
2140 case glslang::EOpConstructMat3x2:
2141 case glslang::EOpConstructMat3x3:
2142 case glslang::EOpConstructMat3x4:
2143 case glslang::EOpConstructMat4x2:
2144 case glslang::EOpConstructMat4x3:
2145 case glslang::EOpConstructMat4x4:
2146 case glslang::EOpConstructDMat2x2:
2147 case glslang::EOpConstructDMat2x3:
2148 case glslang::EOpConstructDMat2x4:
2149 case glslang::EOpConstructDMat3x2:
2150 case glslang::EOpConstructDMat3x3:
2151 case glslang::EOpConstructDMat3x4:
2152 case glslang::EOpConstructDMat4x2:
2153 case glslang::EOpConstructDMat4x3:
2154 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002155 case glslang::EOpConstructIMat2x2:
2156 case glslang::EOpConstructIMat2x3:
2157 case glslang::EOpConstructIMat2x4:
2158 case glslang::EOpConstructIMat3x2:
2159 case glslang::EOpConstructIMat3x3:
2160 case glslang::EOpConstructIMat3x4:
2161 case glslang::EOpConstructIMat4x2:
2162 case glslang::EOpConstructIMat4x3:
2163 case glslang::EOpConstructIMat4x4:
2164 case glslang::EOpConstructUMat2x2:
2165 case glslang::EOpConstructUMat2x3:
2166 case glslang::EOpConstructUMat2x4:
2167 case glslang::EOpConstructUMat3x2:
2168 case glslang::EOpConstructUMat3x3:
2169 case glslang::EOpConstructUMat3x4:
2170 case glslang::EOpConstructUMat4x2:
2171 case glslang::EOpConstructUMat4x3:
2172 case glslang::EOpConstructUMat4x4:
2173 case glslang::EOpConstructBMat2x2:
2174 case glslang::EOpConstructBMat2x3:
2175 case glslang::EOpConstructBMat2x4:
2176 case glslang::EOpConstructBMat3x2:
2177 case glslang::EOpConstructBMat3x3:
2178 case glslang::EOpConstructBMat3x4:
2179 case glslang::EOpConstructBMat4x2:
2180 case glslang::EOpConstructBMat4x3:
2181 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002182 case glslang::EOpConstructF16Mat2x2:
2183 case glslang::EOpConstructF16Mat2x3:
2184 case glslang::EOpConstructF16Mat2x4:
2185 case glslang::EOpConstructF16Mat3x2:
2186 case glslang::EOpConstructF16Mat3x3:
2187 case glslang::EOpConstructF16Mat3x4:
2188 case glslang::EOpConstructF16Mat4x2:
2189 case glslang::EOpConstructF16Mat4x3:
2190 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002191 isMatrix = true;
2192 // fall through
2193 case glslang::EOpConstructFloat:
2194 case glslang::EOpConstructVec2:
2195 case glslang::EOpConstructVec3:
2196 case glslang::EOpConstructVec4:
2197 case glslang::EOpConstructDouble:
2198 case glslang::EOpConstructDVec2:
2199 case glslang::EOpConstructDVec3:
2200 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002201 case glslang::EOpConstructFloat16:
2202 case glslang::EOpConstructF16Vec2:
2203 case glslang::EOpConstructF16Vec3:
2204 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002205 case glslang::EOpConstructBool:
2206 case glslang::EOpConstructBVec2:
2207 case glslang::EOpConstructBVec3:
2208 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002209 case glslang::EOpConstructInt8:
2210 case glslang::EOpConstructI8Vec2:
2211 case glslang::EOpConstructI8Vec3:
2212 case glslang::EOpConstructI8Vec4:
2213 case glslang::EOpConstructUint8:
2214 case glslang::EOpConstructU8Vec2:
2215 case glslang::EOpConstructU8Vec3:
2216 case glslang::EOpConstructU8Vec4:
2217 case glslang::EOpConstructInt16:
2218 case glslang::EOpConstructI16Vec2:
2219 case glslang::EOpConstructI16Vec3:
2220 case glslang::EOpConstructI16Vec4:
2221 case glslang::EOpConstructUint16:
2222 case glslang::EOpConstructU16Vec2:
2223 case glslang::EOpConstructU16Vec3:
2224 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002225 case glslang::EOpConstructInt:
2226 case glslang::EOpConstructIVec2:
2227 case glslang::EOpConstructIVec3:
2228 case glslang::EOpConstructIVec4:
2229 case glslang::EOpConstructUint:
2230 case glslang::EOpConstructUVec2:
2231 case glslang::EOpConstructUVec3:
2232 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002233 case glslang::EOpConstructInt64:
2234 case glslang::EOpConstructI64Vec2:
2235 case glslang::EOpConstructI64Vec3:
2236 case glslang::EOpConstructI64Vec4:
2237 case glslang::EOpConstructUint64:
2238 case glslang::EOpConstructU64Vec2:
2239 case glslang::EOpConstructU64Vec3:
2240 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002241 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002242 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002243 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002244 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002245 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002246 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002247 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002248 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002249 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002250 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002251 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002252 else if (node->getOp() == glslang::EOpConstructStruct ||
2253 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2254 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002255 std::vector<spv::Id> constituents;
2256 for (int c = 0; c < (int)arguments.size(); ++c)
2257 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002258 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002259 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002260 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002261 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002262 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002263
2264 builder.clearAccessChain();
2265 builder.setAccessChainRValue(constructed);
2266
2267 return false;
2268 }
2269
2270 // These six are component-wise compares with component-wise results.
2271 // Forward on to createBinaryOperation(), requesting a vector result.
2272 case glslang::EOpLessThan:
2273 case glslang::EOpGreaterThan:
2274 case glslang::EOpLessThanEqual:
2275 case glslang::EOpGreaterThanEqual:
2276 case glslang::EOpVectorEqual:
2277 case glslang::EOpVectorNotEqual:
2278 {
2279 // Map the operation to a binary
2280 binOp = node->getOp();
2281 reduceComparison = false;
2282 switch (node->getOp()) {
2283 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2284 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2285 default: binOp = node->getOp(); break;
2286 }
2287
2288 break;
2289 }
2290 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002291 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002292 binOp = glslang::EOpMul;
2293 break;
2294 case glslang::EOpOuterProduct:
2295 // two vectors multiplied to make a matrix
2296 binOp = glslang::EOpOuterProduct;
2297 break;
2298 case glslang::EOpDot:
2299 {
qining25262b32016-05-06 17:25:16 -04002300 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002301 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002302 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002303 binOp = glslang::EOpMul;
2304 break;
2305 }
2306 case glslang::EOpMod:
2307 // when an aggregate, this is the floating-point mod built-in function,
2308 // which can be emitted by the one in createBinaryOperation()
2309 binOp = glslang::EOpMod;
2310 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002311 case glslang::EOpEmitVertex:
2312 case glslang::EOpEndPrimitive:
2313 case glslang::EOpBarrier:
2314 case glslang::EOpMemoryBarrier:
2315 case glslang::EOpMemoryBarrierAtomicCounter:
2316 case glslang::EOpMemoryBarrierBuffer:
2317 case glslang::EOpMemoryBarrierImage:
2318 case glslang::EOpMemoryBarrierShared:
2319 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002320 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002321 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002322 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002323 case glslang::EOpWorkgroupMemoryBarrier:
2324 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002325 case glslang::EOpSubgroupBarrier:
2326 case glslang::EOpSubgroupMemoryBarrier:
2327 case glslang::EOpSubgroupMemoryBarrierBuffer:
2328 case glslang::EOpSubgroupMemoryBarrierImage:
2329 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002330 noReturnValue = true;
2331 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2332 break;
2333
Jeff Bolz36831c92018-09-05 10:11:41 -05002334 case glslang::EOpAtomicStore:
2335 noReturnValue = true;
2336 // fallthrough
2337 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002338 case glslang::EOpAtomicAdd:
2339 case glslang::EOpAtomicMin:
2340 case glslang::EOpAtomicMax:
2341 case glslang::EOpAtomicAnd:
2342 case glslang::EOpAtomicOr:
2343 case glslang::EOpAtomicXor:
2344 case glslang::EOpAtomicExchange:
2345 case glslang::EOpAtomicCompSwap:
2346 atomic = true;
2347 break;
2348
John Kessenich0d0c6d32017-07-23 16:08:26 -06002349 case glslang::EOpAtomicCounterAdd:
2350 case glslang::EOpAtomicCounterSubtract:
2351 case glslang::EOpAtomicCounterMin:
2352 case glslang::EOpAtomicCounterMax:
2353 case glslang::EOpAtomicCounterAnd:
2354 case glslang::EOpAtomicCounterOr:
2355 case glslang::EOpAtomicCounterXor:
2356 case glslang::EOpAtomicCounterExchange:
2357 case glslang::EOpAtomicCounterCompSwap:
2358 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2359 builder.addCapability(spv::CapabilityAtomicStorageOps);
2360 atomic = true;
2361 break;
2362
Chao Chen3c366992018-09-19 11:41:59 -07002363#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002364 case glslang::EOpIgnoreIntersectionNV:
2365 case glslang::EOpTerminateRayNV:
2366 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002367 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002368 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2369 noReturnValue = true;
2370 break;
2371#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002372 case glslang::EOpCooperativeMatrixLoad:
2373 case glslang::EOpCooperativeMatrixStore:
2374 noReturnValue = true;
2375 break;
Chao Chen3c366992018-09-19 11:41:59 -07002376
John Kessenich140f3df2015-06-26 16:58:36 -06002377 default:
2378 break;
2379 }
2380
2381 //
2382 // See if it maps to a regular operation.
2383 //
John Kessenich140f3df2015-06-26 16:58:36 -06002384 if (binOp != glslang::EOpNull) {
2385 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2386 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2387 assert(left && right);
2388
2389 builder.clearAccessChain();
2390 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002391 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002392
2393 builder.clearAccessChain();
2394 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002395 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002396
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002397 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002398 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002399 TranslateNoContractionDecoration(node->getType().getQualifier()),
2400 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002401 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002402 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002403 left->getType().getBasicType(), reduceComparison);
2404
2405 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002406 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 builder.clearAccessChain();
2408 builder.setAccessChainRValue(result);
2409
2410 return false;
2411 }
2412
John Kessenich426394d2015-07-23 10:22:48 -06002413 //
2414 // Create the list of operands.
2415 //
John Kessenich140f3df2015-06-26 16:58:36 -06002416 glslang::TIntermSequence& glslangOperands = node->getSequence();
2417 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002418 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002419 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002420 // special case l-value operands; there are just a few
2421 bool lvalue = false;
2422 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002423 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002424 case glslang::EOpModf:
2425 if (arg == 1)
2426 lvalue = true;
2427 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002428 case glslang::EOpInterpolateAtSample:
2429 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002430#ifdef AMD_EXTENSIONS
2431 case glslang::EOpInterpolateAtVertex:
2432#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002433 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002434 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002435
2436 // Does it need a swizzle inversion? If so, evaluation is inverted;
2437 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002438 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002439 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2440 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2441 }
Rex Xu7a26c172015-12-08 17:12:09 +08002442 break;
Rex Xud4782c12015-09-06 16:30:11 +08002443 case glslang::EOpAtomicAdd:
2444 case glslang::EOpAtomicMin:
2445 case glslang::EOpAtomicMax:
2446 case glslang::EOpAtomicAnd:
2447 case glslang::EOpAtomicOr:
2448 case glslang::EOpAtomicXor:
2449 case glslang::EOpAtomicExchange:
2450 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002451 case glslang::EOpAtomicLoad:
2452 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002453 case glslang::EOpAtomicCounterAdd:
2454 case glslang::EOpAtomicCounterSubtract:
2455 case glslang::EOpAtomicCounterMin:
2456 case glslang::EOpAtomicCounterMax:
2457 case glslang::EOpAtomicCounterAnd:
2458 case glslang::EOpAtomicCounterOr:
2459 case glslang::EOpAtomicCounterXor:
2460 case glslang::EOpAtomicCounterExchange:
2461 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002462 if (arg == 0)
2463 lvalue = true;
2464 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002465 case glslang::EOpAddCarry:
2466 case glslang::EOpSubBorrow:
2467 if (arg == 2)
2468 lvalue = true;
2469 break;
2470 case glslang::EOpUMulExtended:
2471 case glslang::EOpIMulExtended:
2472 if (arg >= 2)
2473 lvalue = true;
2474 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002475 case glslang::EOpCooperativeMatrixLoad:
2476 if (arg == 0 || arg == 1)
2477 lvalue = true;
2478 break;
2479 case glslang::EOpCooperativeMatrixStore:
2480 if (arg == 1)
2481 lvalue = true;
2482 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002483 default:
2484 break;
2485 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002486 builder.clearAccessChain();
2487 if (invertedType != spv::NoType && arg == 0)
2488 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2489 else
2490 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002491
2492 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2493 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2494
2495 if (arg == 1) {
2496 // fold "element" parameter into the access chain
2497 spv::Builder::AccessChain save = builder.getAccessChain();
2498 builder.clearAccessChain();
2499 glslangOperands[2]->traverse(this);
2500
2501 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2502
2503 builder.setAccessChain(save);
2504
2505 // Point to the first element of the array.
2506 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2507 getBufferReferenceAlignment(glslangOperands[arg]->getAsTyped()->getType()));
2508
2509 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2510 unsigned int alignment = builder.getAccessChain().alignment;
2511
2512 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2513 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2514 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2515 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2516 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2517 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2518 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2519 }
2520
2521 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2522
2523 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2524 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2525 }
2526
2527 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2528 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2529 }
2530 } else if (arg == 2) {
2531 continue;
2532 }
2533 }
2534
John Kessenich140f3df2015-06-26 16:58:36 -06002535 if (lvalue)
2536 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002537 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002538 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002539 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002540 }
John Kessenich140f3df2015-06-26 16:58:36 -06002541 }
John Kessenich426394d2015-07-23 10:22:48 -06002542
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002543 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002544 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2545 std::vector<spv::IdImmediate> idImmOps;
2546
2547 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2548 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2549 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2550 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2551 // get the pointee type
2552 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2553 assert(builder.isCooperativeMatrixType(typeId));
2554 // do the op
2555 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2556 // store the result to the pointer (out param 'm')
2557 builder.createStore(result, operands[0]);
2558 result = 0;
2559 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2560 std::vector<spv::IdImmediate> idImmOps;
2561
2562 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2563 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2564 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2565 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2566 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2567
2568 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2569 result = 0;
2570 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002571 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002572 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002573 } else {
2574 // Pass through to generic operations.
2575 switch (glslangOperands.size()) {
2576 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002577 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002578 break;
2579 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002580 {
2581 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002582 TranslateNoContractionDecoration(node->getType().getQualifier()),
2583 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002584 result = createUnaryOperation(
2585 node->getOp(), decorations,
2586 resultType(), operands.front(),
2587 glslangOperands[0]->getAsTyped()->getBasicType());
2588 }
John Kessenich426394d2015-07-23 10:22:48 -06002589 break;
2590 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002591 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002592 break;
2593 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002594 if (invertedType)
2595 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002596 }
2597
2598 if (noReturnValue)
2599 return false;
2600
2601 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002602 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002603 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002604 } else {
2605 builder.clearAccessChain();
2606 builder.setAccessChainRValue(result);
2607 return false;
2608 }
2609}
2610
John Kessenich433e9ff2017-01-26 20:31:11 -07002611// This path handles both if-then-else and ?:
2612// The if-then-else has a node type of void, while
2613// ?: has either a void or a non-void node type
2614//
2615// Leaving the result, when not void:
2616// GLSL only has r-values as the result of a :?, but
2617// if we have an l-value, that can be more efficient if it will
2618// become the base of a complex r-value expression, because the
2619// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002620bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2621{
John Kessenich4bee5312018-02-20 21:29:05 -07002622 // See if it simple and safe, or required, to execute both sides.
2623 // Crucially, side effects must be either semantically required or avoided,
2624 // and there are performance trade-offs.
2625 // Return true if required or a good idea (and safe) to execute both sides,
2626 // false otherwise.
2627 const auto bothSidesPolicy = [&]() -> bool {
2628 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002629 if (node->getTrueBlock() == nullptr ||
2630 node->getFalseBlock() == nullptr)
2631 return false;
2632
John Kessenich4bee5312018-02-20 21:29:05 -07002633 // required? (unless we write additional code to look for side effects
2634 // and make performance trade-offs if none are present)
2635 if (!node->getShortCircuit())
2636 return true;
2637
2638 // if not required to execute both, decide based on performance/practicality...
2639
2640 // see if OpSelect can handle it
2641 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2642 node->getBasicType() == glslang::EbtVoid)
2643 return false;
2644
John Kessenich433e9ff2017-01-26 20:31:11 -07002645 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2646 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2647
2648 // return true if a single operand to ? : is okay for OpSelect
2649 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002650 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002651 };
2652
2653 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2654 operandOkay(node->getFalseBlock()->getAsTyped());
2655 };
2656
John Kessenich4bee5312018-02-20 21:29:05 -07002657 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2658 // emit the condition before doing anything with selection
2659 node->getCondition()->traverse(this);
2660 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2661
2662 // Find a way of executing both sides and selecting the right result.
2663 const auto executeBothSides = [&]() -> void {
2664 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002665 node->getTrueBlock()->traverse(this);
2666 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2667 node->getFalseBlock()->traverse(this);
2668 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2669
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002670 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002671
John Kessenich4bee5312018-02-20 21:29:05 -07002672 // done if void
2673 if (node->getBasicType() == glslang::EbtVoid)
2674 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002675
John Kessenich4bee5312018-02-20 21:29:05 -07002676 // emit code to select between trueValue and falseValue
2677
2678 // see if OpSelect can handle it
2679 if (node->getType().isScalar() || node->getType().isVector()) {
2680 // Emit OpSelect for this selection.
2681
2682 // smear condition to vector, if necessary (AST is always scalar)
2683 if (builder.isVector(trueValue))
2684 condition = builder.smearScalar(spv::NoPrecision, condition,
2685 builder.makeVectorType(builder.makeBoolType(),
2686 builder.getNumComponents(trueValue)));
2687
2688 // OpSelect
2689 result = builder.createTriOp(spv::OpSelect,
2690 convertGlslangToSpvType(node->getType()), condition,
2691 trueValue, falseValue);
2692
2693 builder.clearAccessChain();
2694 builder.setAccessChainRValue(result);
2695 } else {
2696 // We need control flow to select the result.
2697 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2698 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2699
2700 // Selection control:
2701 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2702
2703 // make an "if" based on the value created by the condition
2704 spv::Builder::If ifBuilder(condition, control, builder);
2705
2706 // emit the "then" statement
2707 builder.createStore(trueValue, result);
2708 ifBuilder.makeBeginElse();
2709 // emit the "else" statement
2710 builder.createStore(falseValue, result);
2711
2712 // finish off the control flow
2713 ifBuilder.makeEndIf();
2714
2715 builder.clearAccessChain();
2716 builder.setAccessChainLValue(result);
2717 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002718 };
2719
John Kessenich4bee5312018-02-20 21:29:05 -07002720 // Execute the one side needed, as per the condition
2721 const auto executeOneSide = [&]() {
2722 // Always emit control flow.
2723 if (node->getBasicType() != glslang::EbtVoid)
2724 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002725
John Kessenich4bee5312018-02-20 21:29:05 -07002726 // Selection control:
2727 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2728
2729 // make an "if" based on the value created by the condition
2730 spv::Builder::If ifBuilder(condition, control, builder);
2731
2732 // emit the "then" statement
2733 if (node->getTrueBlock() != nullptr) {
2734 node->getTrueBlock()->traverse(this);
2735 if (result != spv::NoResult)
2736 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2737 }
2738
2739 if (node->getFalseBlock() != nullptr) {
2740 ifBuilder.makeBeginElse();
2741 // emit the "else" statement
2742 node->getFalseBlock()->traverse(this);
2743 if (result != spv::NoResult)
2744 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2745 }
2746
2747 // finish off the control flow
2748 ifBuilder.makeEndIf();
2749
2750 if (result != spv::NoResult) {
2751 builder.clearAccessChain();
2752 builder.setAccessChainLValue(result);
2753 }
2754 };
2755
2756 // Try for OpSelect (or a requirement to execute both sides)
2757 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002758 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2759 if (node->getType().getQualifier().isSpecConstant())
2760 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002761 executeBothSides();
2762 } else
2763 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002764
2765 return false;
2766}
2767
2768bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2769{
2770 // emit and get the condition before doing anything with switch
2771 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002772 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002773
Rex Xu57e65922017-07-04 23:23:40 +08002774 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002775 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002776
John Kessenich140f3df2015-06-26 16:58:36 -06002777 // browse the children to sort out code segments
2778 int defaultSegment = -1;
2779 std::vector<TIntermNode*> codeSegments;
2780 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2781 std::vector<int> caseValues;
2782 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2783 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2784 TIntermNode* child = *c;
2785 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002786 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002787 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002788 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002789 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2790 } else
2791 codeSegments.push_back(child);
2792 }
2793
qining25262b32016-05-06 17:25:16 -04002794 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002795 // statements between the last case and the end of the switch statement
2796 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2797 (int)codeSegments.size() == defaultSegment)
2798 codeSegments.push_back(nullptr);
2799
2800 // make the switch statement
2801 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002802 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002803
2804 // emit all the code in the segments
2805 breakForLoop.push(false);
2806 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2807 builder.nextSwitchSegment(segmentBlocks, s);
2808 if (codeSegments[s])
2809 codeSegments[s]->traverse(this);
2810 else
2811 builder.addSwitchBreak();
2812 }
2813 breakForLoop.pop();
2814
2815 builder.endSwitch(segmentBlocks);
2816
2817 return false;
2818}
2819
2820void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2821{
2822 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002823 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002824
2825 builder.clearAccessChain();
2826 builder.setAccessChainRValue(constant);
2827}
2828
2829bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2830{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002831 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002832 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002833
2834 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002835 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2836 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002837
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002838 // Spec requires back edges to target header blocks, and every header block
2839 // must dominate its merge block. Make a header block first to ensure these
2840 // conditions are met. By definition, it will contain OpLoopMerge, followed
2841 // by a block-ending branch. But we don't want to put any other body/test
2842 // instructions in it, since the body/test may have arbitrary instructions,
2843 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002844 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002845 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002846 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002847 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002848 spv::Block& test = builder.makeNewBlock();
2849 builder.createBranch(&test);
2850
2851 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002852 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002853 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002854 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2855
2856 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002857 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002858 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002859 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002860 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002861 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002862
2863 builder.setBuildPoint(&blocks.continue_target);
2864 if (node->getTerminal())
2865 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002866 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002867 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002868 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002869 builder.createBranch(&blocks.body);
2870
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002871 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002872 builder.setBuildPoint(&blocks.body);
2873 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002874 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002875 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002876 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002877
2878 builder.setBuildPoint(&blocks.continue_target);
2879 if (node->getTerminal())
2880 node->getTerminal()->traverse(this);
2881 if (node->getTest()) {
2882 node->getTest()->traverse(this);
2883 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002884 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002885 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002886 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002887 // TODO: unless there was a break/return/discard instruction
2888 // somewhere in the body, this is an infinite loop, so we should
2889 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002890 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002891 }
John Kessenich140f3df2015-06-26 16:58:36 -06002892 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002893 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002894 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002895 return false;
2896}
2897
2898bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2899{
2900 if (node->getExpression())
2901 node->getExpression()->traverse(this);
2902
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002903 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002904
John Kessenich140f3df2015-06-26 16:58:36 -06002905 switch (node->getFlowOp()) {
2906 case glslang::EOpKill:
2907 builder.makeDiscard();
2908 break;
2909 case glslang::EOpBreak:
2910 if (breakForLoop.top())
2911 builder.createLoopExit();
2912 else
2913 builder.addSwitchBreak();
2914 break;
2915 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002916 builder.createLoopContinue();
2917 break;
2918 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002919 if (node->getExpression()) {
2920 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2921 spv::Id returnId = accessChainLoad(glslangReturnType);
2922 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2923 builder.clearAccessChain();
2924 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2925 builder.setAccessChainLValue(copyId);
2926 multiTypeStore(glslangReturnType, returnId);
2927 returnId = builder.createLoad(copyId);
2928 }
2929 builder.makeReturn(false, returnId);
2930 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002931 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002932
2933 builder.clearAccessChain();
2934 break;
2935
2936 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002937 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002938 break;
2939 }
2940
2941 return false;
2942}
2943
2944spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2945{
qining25262b32016-05-06 17:25:16 -04002946 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002947 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002948 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002949 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002950 spv::Id result = createSpvConstant(*node);
2951 if (result != spv::NoResult)
2952 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002953 }
2954
2955 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002956 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002957 spv::Id spvType = convertGlslangToSpvType(node->getType());
2958
Rex Xucabbb782017-03-24 13:41:14 +08002959 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2960 node->getType().containsBasicType(glslang::EbtInt16) ||
2961 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002962 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002963 switch (storageClass) {
2964 case spv::StorageClassInput:
2965 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002966 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002967 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002968 break;
2969 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002970 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002971 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002972 break;
2973 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002974 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002975 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2976 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002977 else
2978 builder.addCapability(spv::CapabilityStorageUniform16);
2979 break;
2980 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002981 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002982 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2983 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2984 break;
2985 default:
2986 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002987 }
2988 }
Rex Xuf89ad982017-04-07 23:22:33 +08002989
John Kessenich312dcfb2018-07-03 13:19:51 -06002990 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2991 node->getType().containsBasicType(glslang::EbtUint8);
2992 if (contains8BitType) {
2993 if (storageClass == spv::StorageClassPushConstant) {
2994 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2995 builder.addCapability(spv::CapabilityStoragePushConstant8);
2996 } else if (storageClass == spv::StorageClassUniform) {
2997 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2998 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002999 } else if (storageClass == spv::StorageClassStorageBuffer) {
3000 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3001 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003002 }
3003 }
3004
John Kessenich140f3df2015-06-26 16:58:36 -06003005 const char* name = node->getName().c_str();
3006 if (glslang::IsAnonymous(name))
3007 name = "";
3008
3009 return builder.createVariable(storageClass, spvType, name);
3010}
3011
3012// Return type Id of the sampled type.
3013spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3014{
3015 switch (sampler.type) {
3016 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003017#ifdef AMD_EXTENSIONS
3018 case glslang::EbtFloat16:
3019 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3020 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3021 return builder.makeFloatType(16);
3022#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003023 case glslang::EbtInt: return builder.makeIntType(32);
3024 case glslang::EbtUint: return builder.makeUintType(32);
3025 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003026 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003027 return builder.makeFloatType(32);
3028 }
3029}
3030
John Kessenich8c8505c2016-07-26 12:50:38 -06003031// If node is a swizzle operation, return the type that should be used if
3032// the swizzle base is first consumed by another operation, before the swizzle
3033// is applied.
3034spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3035{
John Kessenichecba76f2017-01-06 00:34:48 -07003036 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003037 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3038 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3039 else
3040 return spv::NoType;
3041}
3042
3043// When inverting a swizzle with a parent op, this function
3044// will apply the swizzle operation to a completed parent operation.
3045spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3046{
3047 std::vector<unsigned> swizzle;
3048 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3049 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3050}
3051
John Kessenich8c8505c2016-07-26 12:50:38 -06003052// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3053void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3054{
3055 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3056 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3057 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3058}
3059
John Kessenich3ac051e2015-12-20 11:29:16 -07003060// Convert from a glslang type to an SPV type, by calling into a
3061// recursive version of this function. This establishes the inherited
3062// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003063spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003064{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003065 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003066}
3067
3068// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003069// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003070// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003071spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003072 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3073 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003074{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003075 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003076
3077 switch (type.getBasicType()) {
3078 case glslang::EbtVoid:
3079 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003080 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
3082 case glslang::EbtFloat:
3083 spvType = builder.makeFloatType(32);
3084 break;
3085 case glslang::EbtDouble:
3086 spvType = builder.makeFloatType(64);
3087 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003088 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003089 spvType = builder.makeFloatType(16);
3090 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003092 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3093 // a 32-bit int where non-0 means true.
3094 if (explicitLayout != glslang::ElpNone)
3095 spvType = builder.makeUintType(32);
3096 else
3097 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003098 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003099 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003100 spvType = builder.makeIntType(8);
3101 break;
3102 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003103 spvType = builder.makeUintType(8);
3104 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003105 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003106 spvType = builder.makeIntType(16);
3107 break;
3108 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003109 spvType = builder.makeUintType(16);
3110 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003111 case glslang::EbtInt:
3112 spvType = builder.makeIntType(32);
3113 break;
3114 case glslang::EbtUint:
3115 spvType = builder.makeUintType(32);
3116 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003117 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003118 spvType = builder.makeIntType(64);
3119 break;
3120 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003121 spvType = builder.makeUintType(64);
3122 break;
John Kessenich426394d2015-07-23 10:22:48 -06003123 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003124 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003125 spvType = builder.makeUintType(32);
3126 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003127#ifdef NV_EXTENSIONS
3128 case glslang::EbtAccStructNV:
3129 spvType = builder.makeAccelerationStructureNVType();
3130 break;
3131#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003132 case glslang::EbtSampler:
3133 {
3134 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003135 if (sampler.sampler) {
3136 // pure sampler
3137 spvType = builder.makeSamplerType();
3138 } else {
3139 // an image is present, make its type
3140 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3141 sampler.image ? 2 : 1, TranslateImageFormat(type));
3142 if (sampler.combined) {
3143 // already has both image and sampler, make the combined type
3144 spvType = builder.makeSampledImageType(spvType);
3145 }
John Kessenich55e7d112015-11-15 21:33:39 -07003146 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003147 }
John Kessenich140f3df2015-06-26 16:58:36 -06003148 break;
3149 case glslang::EbtStruct:
3150 case glslang::EbtBlock:
3151 {
3152 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003153 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003154
3155 // Try to share structs for different layouts, but not yet for other
3156 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003157 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003158 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003159 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161
3162 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003163 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003164 memberRemapper[glslangMembers].resize(glslangMembers->size());
3165 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003166 }
3167 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003168 case glslang::EbtReference:
3169 {
3170 // Make the forward pointer, then recurse to convert the structure type, then
3171 // patch up the forward pointer with a real pointer type.
3172 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3173 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3174 forwardPointers[type.getReferentType()] = forwardId;
3175 }
3176 spvType = forwardPointers[type.getReferentType()];
3177 if (!forwardReferenceOnly) {
3178 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3179 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3180 forwardPointers[type.getReferentType()],
3181 referentType);
3182 }
3183 }
3184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003186 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003187 break;
3188 }
3189
3190 if (type.isMatrix())
3191 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3192 else {
3193 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3194 if (type.getVectorSize() > 1)
3195 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3196 }
3197
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003198 if (type.isCoopMat()) {
3199 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3200 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3201 if (type.getBasicType() == glslang::EbtFloat16)
3202 builder.addCapability(spv::CapabilityFloat16);
3203
3204 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3205 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3206 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3207
3208 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3209 }
3210
John Kessenich140f3df2015-06-26 16:58:36 -06003211 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003212 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3213
John Kessenichc9a80832015-09-12 12:17:44 -06003214 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003215 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003216 // We need to decorate array strides for types needing explicit layout, except blocks.
3217 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003218 // Use a dummy glslang type for querying internal strides of
3219 // arrays of arrays, but using just a one-dimensional array.
3220 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003221 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3222 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003223
3224 // Will compute the higher-order strides here, rather than making a whole
3225 // pile of types and doing repetitive recursion on their contents.
3226 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3227 }
John Kessenichf8842e52016-01-04 19:22:56 -07003228
3229 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003230 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003231 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003232 if (stride > 0)
3233 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003234 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003235 }
3236 } else {
3237 // single-dimensional array, and don't yet have stride
3238
John Kessenichf8842e52016-01-04 19:22:56 -07003239 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003240 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3241 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003242 }
John Kessenich31ed4832015-09-09 17:51:38 -06003243
John Kessenichead86222018-03-28 18:01:20 -06003244 // Do the outer dimension, which might not be known for a runtime-sized array.
3245 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3246 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003247 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003248 else {
3249 if (!lastBufferBlockMember) {
3250 builder.addExtension("SPV_EXT_descriptor_indexing");
3251 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3252 }
John Kessenichead86222018-03-28 18:01:20 -06003253 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003254 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003255 if (stride > 0)
3256 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003257 }
3258
3259 return spvType;
3260}
3261
John Kessenich0e737842017-03-24 18:38:16 -06003262// TODO: this functionality should exist at a higher level, in creating the AST
3263//
3264// Identify interface members that don't have their required extension turned on.
3265//
3266bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3267{
Chao Chen3c366992018-09-19 11:41:59 -07003268#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003269 auto& extensions = glslangIntermediate->getRequestedExtensions();
3270
Rex Xubcf291a2017-03-29 23:01:36 +08003271 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3272 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3273 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003274 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3275 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3276 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003277
3278 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3279 if (member.getFieldName() == "gl_ViewportMask" &&
3280 extensions.find("GL_NV_viewport_array2") == extensions.end())
3281 return true;
3282 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3283 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3284 return true;
3285 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3286 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3287 return true;
3288 }
3289#endif
John Kessenich0e737842017-03-24 18:38:16 -06003290
3291 return false;
3292};
3293
John Kessenich6090df02016-06-30 21:18:02 -06003294// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3295// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3296// Mutually recursive with convertGlslangToSpvType().
3297spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3298 const glslang::TTypeList* glslangMembers,
3299 glslang::TLayoutPacking explicitLayout,
3300 const glslang::TQualifier& qualifier)
3301{
3302 // Create a vector of struct types for SPIR-V to consume
3303 std::vector<spv::Id> spvMembers;
3304 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003305 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003306 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3307 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3308 if (glslangMember.hiddenMember()) {
3309 ++memberDelta;
3310 if (type.getBasicType() == glslang::EbtBlock)
3311 memberRemapper[glslangMembers][i] = -1;
3312 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003313 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003314 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003315 if (filterMember(glslangMember))
3316 continue;
3317 }
John Kessenich6090df02016-06-30 21:18:02 -06003318 // modify just this child's view of the qualifier
3319 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3320 InheritQualifiers(memberQualifier, qualifier);
3321
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003322 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003323 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003324 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003325
3326 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003327 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3328 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003329
3330 // Make forward pointers for any pointer members, and create a list of members to
3331 // convert to spirv types after creating the struct.
3332 if (glslangMember.getBasicType() == glslang::EbtReference) {
3333 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3334 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3335 }
3336 spvMembers.push_back(
3337 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3338 } else {
3339 spvMembers.push_back(
3340 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3341 }
John Kessenich6090df02016-06-30 21:18:02 -06003342 }
3343 }
3344
3345 // Make the SPIR-V type
3346 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003347 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003348 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3349
3350 // Decorate it
3351 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3352
John Kessenichd72f4882019-01-16 14:55:37 +07003353 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003354 auto it = deferredForwardPointers[i];
3355 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3356 }
3357
John Kessenich6090df02016-06-30 21:18:02 -06003358 return spvType;
3359}
3360
3361void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3362 const glslang::TTypeList* glslangMembers,
3363 glslang::TLayoutPacking explicitLayout,
3364 const glslang::TQualifier& qualifier,
3365 spv::Id spvType)
3366{
3367 // Name and decorate the non-hidden members
3368 int offset = -1;
3369 int locationOffset = 0; // for use within the members of this struct
3370 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3371 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3372 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003373 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003374 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003375 if (filterMember(glslangMember))
3376 continue;
3377 }
John Kessenich6090df02016-06-30 21:18:02 -06003378
3379 // modify just this child's view of the qualifier
3380 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3381 InheritQualifiers(memberQualifier, qualifier);
3382
3383 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003384 if (member < 0)
3385 continue;
3386
3387 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3388 builder.addMemberDecoration(spvType, member,
3389 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3390 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3391 // Add interpolation and auxiliary storage decorations only to
3392 // top-level members of Input and Output storage classes
3393 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3394 type.getQualifier().storage == glslang::EvqVaryingOut) {
3395 if (type.getBasicType() == glslang::EbtBlock ||
3396 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3397 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3398 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003399#ifdef NV_EXTENSIONS
3400 addMeshNVDecoration(spvType, member, memberQualifier);
3401#endif
John Kessenich6090df02016-06-30 21:18:02 -06003402 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003403 }
3404 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003405
John Kessenich5d610ee2018-03-07 18:05:55 -07003406 if (type.getBasicType() == glslang::EbtBlock &&
3407 qualifier.storage == glslang::EvqBuffer) {
3408 // Add memory decorations only to top-level members of shader storage block
3409 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003410 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003411 for (unsigned int i = 0; i < memory.size(); ++i)
3412 builder.addMemberDecoration(spvType, member, memory[i]);
3413 }
John Kessenich6090df02016-06-30 21:18:02 -06003414
John Kessenich5d610ee2018-03-07 18:05:55 -07003415 // Location assignment was already completed correctly by the front end,
3416 // just track whether a member needs to be decorated.
3417 // Ignore member locations if the container is an array, as that's
3418 // ill-specified and decisions have been made to not allow this.
3419 if (! type.isArray() && memberQualifier.hasLocation())
3420 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003421
John Kessenich5d610ee2018-03-07 18:05:55 -07003422 if (qualifier.hasLocation()) // track for upcoming inheritance
3423 locationOffset += glslangIntermediate->computeTypeLocationSize(
3424 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003425
John Kessenich5d610ee2018-03-07 18:05:55 -07003426 // component, XFB, others
3427 if (glslangMember.getQualifier().hasComponent())
3428 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3429 glslangMember.getQualifier().layoutComponent);
3430 if (glslangMember.getQualifier().hasXfbOffset())
3431 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3432 glslangMember.getQualifier().layoutXfbOffset);
3433 else if (explicitLayout != glslang::ElpNone) {
3434 // figure out what to do with offset, which is accumulating
3435 int nextOffset;
3436 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3437 if (offset >= 0)
3438 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3439 offset = nextOffset;
3440 }
John Kessenich6090df02016-06-30 21:18:02 -06003441
John Kessenich5d610ee2018-03-07 18:05:55 -07003442 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3443 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3444 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003445
John Kessenich5d610ee2018-03-07 18:05:55 -07003446 // built-in variable decorations
3447 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3448 if (builtIn != spv::BuiltInMax)
3449 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003450
John Kessenich5611c6d2018-04-05 11:25:02 -06003451 // nonuniform
3452 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3453
John Kessenichead86222018-03-28 18:01:20 -06003454 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3455 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3456 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3457 memberQualifier.semanticName);
3458 }
3459
chaoc771d89f2017-01-13 01:10:53 -08003460#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003461 if (builtIn == spv::BuiltInLayer) {
3462 // SPV_NV_viewport_array2 extension
3463 if (glslangMember.getQualifier().layoutViewportRelative){
3464 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3465 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3466 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003467 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003468 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3469 builder.addMemberDecoration(spvType, member,
3470 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3471 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3472 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3473 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003474 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003475 }
3476 if (glslangMember.getQualifier().layoutPassthrough) {
3477 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3478 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3479 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3480 }
chaoc771d89f2017-01-13 01:10:53 -08003481#endif
John Kessenich6090df02016-06-30 21:18:02 -06003482 }
3483
3484 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003485 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3486 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003487}
3488
John Kessenich6c292d32016-02-15 20:58:50 -07003489// Turn the expression forming the array size into an id.
3490// This is not quite trivial, because of specialization constants.
3491// Sometimes, a raw constant is turned into an Id, and sometimes
3492// a specialization constant expression is.
3493spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3494{
3495 // First, see if this is sized with a node, meaning a specialization constant:
3496 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3497 if (specNode != nullptr) {
3498 builder.clearAccessChain();
3499 specNode->traverse(this);
3500 return accessChainLoad(specNode->getAsTyped()->getType());
3501 }
qining25262b32016-05-06 17:25:16 -04003502
John Kessenich6c292d32016-02-15 20:58:50 -07003503 // Otherwise, need a compile-time (front end) size, get it:
3504 int size = arraySizes.getDimSize(dim);
3505 assert(size > 0);
3506 return builder.makeUintConstant(size);
3507}
3508
John Kessenich103bef92016-02-08 21:38:15 -07003509// Wrap the builder's accessChainLoad to:
3510// - localize handling of RelaxedPrecision
3511// - use the SPIR-V inferred type instead of another conversion of the glslang type
3512// (avoids unnecessary work and possible type punning for structures)
3513// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003514spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3515{
John Kessenich103bef92016-02-08 21:38:15 -07003516 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003517
3518 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3519 coherentFlags |= TranslateCoherent(type);
3520
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003521 unsigned int alignment = builder.getAccessChain().alignment;
3522 alignment |= getBufferReferenceAlignment(type);
3523
John Kessenich5611c6d2018-04-05 11:25:02 -06003524 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003525 TranslateNonUniformDecoration(type.getQualifier()),
3526 nominalTypeId,
3527 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003528 TranslateMemoryScope(coherentFlags),
3529 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003530
3531 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003532 if (type.getBasicType() == glslang::EbtBool) {
3533 if (builder.isScalarType(nominalTypeId)) {
3534 // Conversion for bool
3535 spv::Id boolType = builder.makeBoolType();
3536 if (nominalTypeId != boolType)
3537 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3538 } else if (builder.isVectorType(nominalTypeId)) {
3539 // Conversion for bvec
3540 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3541 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3542 if (nominalTypeId != bvecType)
3543 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3544 }
3545 }
John Kessenich103bef92016-02-08 21:38:15 -07003546
3547 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003548}
3549
Rex Xu27253232016-02-23 17:51:09 +08003550// Wrap the builder's accessChainStore to:
3551// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003552//
3553// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003554void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3555{
3556 // Need to convert to abstract types when necessary
3557 if (type.getBasicType() == glslang::EbtBool) {
3558 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3559
3560 if (builder.isScalarType(nominalTypeId)) {
3561 // Conversion for bool
3562 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003563 if (nominalTypeId != boolType) {
3564 // keep these outside arguments, for determinant order-of-evaluation
3565 spv::Id one = builder.makeUintConstant(1);
3566 spv::Id zero = builder.makeUintConstant(0);
3567 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3568 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003569 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003570 } else if (builder.isVectorType(nominalTypeId)) {
3571 // Conversion for bvec
3572 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3573 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003574 if (nominalTypeId != bvecType) {
3575 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003576 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3577 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3578 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003579 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003580 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3581 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003582 }
3583 }
3584
Jeff Bolz36831c92018-09-05 10:11:41 -05003585 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3586 coherentFlags |= TranslateCoherent(type);
3587
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003588 unsigned int alignment = builder.getAccessChain().alignment;
3589 alignment |= getBufferReferenceAlignment(type);
3590
Jeff Bolz36831c92018-09-05 10:11:41 -05003591 builder.accessChainStore(rvalue,
3592 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003593 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003594}
3595
John Kessenich4bf71552016-09-02 11:20:21 -06003596// For storing when types match at the glslang level, but not might match at the
3597// SPIR-V level.
3598//
3599// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003600// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003601// as in a member-decorated way.
3602//
3603// NOTE: This function can handle any store request; if it's not special it
3604// simplifies to a simple OpStore.
3605//
3606// Implicitly uses the existing builder.accessChain as the storage target.
3607void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3608{
John Kessenichb3e24e42016-09-11 12:33:43 -06003609 // we only do the complex path here if it's an aggregate
3610 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003611 accessChainStore(type, rValue);
3612 return;
3613 }
3614
John Kessenichb3e24e42016-09-11 12:33:43 -06003615 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003616 spv::Id rType = builder.getTypeId(rValue);
3617 spv::Id lValue = builder.accessChainGetLValue();
3618 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3619 if (lType == rType) {
3620 accessChainStore(type, rValue);
3621 return;
3622 }
3623
John Kessenichb3e24e42016-09-11 12:33:43 -06003624 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003625 // where the two types were the same type in GLSL. This requires member
3626 // by member copy, recursively.
3627
John Kessenichb3e24e42016-09-11 12:33:43 -06003628 // If an array, copy element by element.
3629 if (type.isArray()) {
3630 glslang::TType glslangElementType(type, 0);
3631 spv::Id elementRType = builder.getContainedTypeId(rType);
3632 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3633 // get the source member
3634 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003635
John Kessenichb3e24e42016-09-11 12:33:43 -06003636 // set up the target storage
3637 builder.clearAccessChain();
3638 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003639 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003640
John Kessenichb3e24e42016-09-11 12:33:43 -06003641 // store the member
3642 multiTypeStore(glslangElementType, elementRValue);
3643 }
3644 } else {
3645 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003646
John Kessenichb3e24e42016-09-11 12:33:43 -06003647 // loop over structure members
3648 const glslang::TTypeList& members = *type.getStruct();
3649 for (int m = 0; m < (int)members.size(); ++m) {
3650 const glslang::TType& glslangMemberType = *members[m].type;
3651
3652 // get the source member
3653 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3654 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3655
3656 // set up the target storage
3657 builder.clearAccessChain();
3658 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003659 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003660
3661 // store the member
3662 multiTypeStore(glslangMemberType, memberRValue);
3663 }
John Kessenich4bf71552016-09-02 11:20:21 -06003664 }
3665}
3666
John Kessenichf85e8062015-12-19 13:57:10 -07003667// Decide whether or not this type should be
3668// decorated with offsets and strides, and if so
3669// whether std140 or std430 rules should be applied.
3670glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003671{
John Kessenichf85e8062015-12-19 13:57:10 -07003672 // has to be a block
3673 if (type.getBasicType() != glslang::EbtBlock)
3674 return glslang::ElpNone;
3675
Chao Chen3c366992018-09-19 11:41:59 -07003676 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003677 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003678 type.getQualifier().storage != glslang::EvqBuffer &&
3679 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003680 return glslang::ElpNone;
3681
3682 // return the layout to use
3683 switch (type.getQualifier().layoutPacking) {
3684 case glslang::ElpStd140:
3685 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003686 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003687 return type.getQualifier().layoutPacking;
3688 default:
3689 return glslang::ElpNone;
3690 }
John Kessenich31ed4832015-09-09 17:51:38 -06003691}
3692
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003693// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003694int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003695{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003696 int size;
John Kessenich49987892015-12-29 17:11:44 -07003697 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003698 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003699
3700 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003701}
3702
John Kessenich49987892015-12-29 17:11:44 -07003703// 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 -07003704// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003705int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003706{
John Kessenich49987892015-12-29 17:11:44 -07003707 glslang::TType elementType;
3708 elementType.shallowCopy(matrixType);
3709 elementType.clearArraySizes();
3710
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003711 int size;
John Kessenich49987892015-12-29 17:11:44 -07003712 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003713 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003714
3715 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003716}
3717
John Kessenich5e4b1242015-08-06 22:53:06 -06003718// Given a member type of a struct, realign the current offset for it, and compute
3719// the next (not yet aligned) offset for the next member, which will get aligned
3720// on the next call.
3721// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3722// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3723// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003724void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003725 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003726{
3727 // this will get a positive value when deemed necessary
3728 nextOffset = -1;
3729
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 // override anything in currentOffset with user-set offset
3731 if (memberType.getQualifier().hasOffset())
3732 currentOffset = memberType.getQualifier().layoutOffset;
3733
3734 // It could be that current linker usage in glslang updated all the layoutOffset,
3735 // in which case the following code does not matter. But, that's not quite right
3736 // once cross-compilation unit GLSL validation is done, as the original user
3737 // settings are needed in layoutOffset, and then the following will come into play.
3738
John Kessenichf85e8062015-12-19 13:57:10 -07003739 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 if (! memberType.getQualifier().hasOffset())
3741 currentOffset = -1;
3742
3743 return;
3744 }
3745
John Kessenichf85e8062015-12-19 13:57:10 -07003746 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003747 if (currentOffset < 0)
3748 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003749
John Kessenich5e4b1242015-08-06 22:53:06 -06003750 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3751 // but possibly not yet correctly aligned.
3752
3753 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003754 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003755 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003756
3757 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003758 // TODO: make this consistent in early phases of code:
3759 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3760 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3761 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003762 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003763 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003764 int dummySize;
3765 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3766 if (componentAlignment <= 4)
3767 memberAlignment = componentAlignment;
3768 }
3769
3770 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003772
3773 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003774 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003775 glslang::RoundToPow2(currentOffset, 16);
3776
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 nextOffset = currentOffset + memberSize;
3778}
3779
David Netoa901ffe2016-06-08 14:11:40 +01003780void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003781{
David Netoa901ffe2016-06-08 14:11:40 +01003782 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3783 switch (glslangBuiltIn)
3784 {
3785 case glslang::EbvClipDistance:
3786 case glslang::EbvCullDistance:
3787 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003788#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003789 case glslang::EbvViewportMaskNV:
3790 case glslang::EbvSecondaryPositionNV:
3791 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003792 case glslang::EbvPositionPerViewNV:
3793 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003794 case glslang::EbvTaskCountNV:
3795 case glslang::EbvPrimitiveCountNV:
3796 case glslang::EbvPrimitiveIndicesNV:
3797 case glslang::EbvClipDistancePerViewNV:
3798 case glslang::EbvCullDistancePerViewNV:
3799 case glslang::EbvLayerPerViewNV:
3800 case glslang::EbvMeshViewCountNV:
3801 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003802#endif
David Netoa901ffe2016-06-08 14:11:40 +01003803 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3804 // Alternately, we could just call this for any glslang built-in, since the
3805 // capability already guards against duplicates.
3806 TranslateBuiltInDecoration(glslangBuiltIn, false);
3807 break;
3808 default:
3809 // Capabilities were already generated when the struct was declared.
3810 break;
3811 }
John Kessenichebb50532016-05-16 19:22:05 -06003812}
3813
John Kessenich6fccb3c2016-09-19 16:01:41 -06003814bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003815{
John Kessenicheee9d532016-09-19 18:09:30 -06003816 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003817}
3818
John Kessenichd41993d2017-09-10 15:21:05 -06003819// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003820// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3821// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003822bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003823{
John Kessenich6a14f782017-12-04 02:48:10 -07003824 assert(qualifier == glslang::EvqIn ||
3825 qualifier == glslang::EvqOut ||
3826 qualifier == glslang::EvqInOut ||
3827 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003828 return qualifier != glslang::EvqConstReadOnly;
3829}
3830
3831// Is parameter pass-by-original?
3832bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3833 bool implicitThisParam)
3834{
3835 if (implicitThisParam) // implicit this
3836 return true;
3837 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003838 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003839 return paramType.containsOpaque() || // sampler, etc.
3840 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3841}
3842
John Kessenich140f3df2015-06-26 16:58:36 -06003843// Make all the functions, skeletally, without actually visiting their bodies.
3844void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3845{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003846 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003847 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3848 if (paramPrecision != spv::NoPrecision)
3849 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003850 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003851 if (type.getBasicType() == glslang::EbtReference) {
3852 // Original and non-writable params pass the pointer directly and
3853 // use restrict/aliased, others are stored to a pointer in Function
3854 // memory and use RestrictPointer/AliasedPointer.
3855 if (originalParam(type.getQualifier().storage, type, false) ||
3856 !writableParam(type.getQualifier().storage)) {
3857 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3858 } else {
3859 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3860 }
3861 }
John Kessenichfad62972017-07-18 02:35:46 -06003862 };
3863
John Kessenich140f3df2015-06-26 16:58:36 -06003864 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3865 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003866 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003867 continue;
3868
3869 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003870 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003871 //
qining25262b32016-05-06 17:25:16 -04003872 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003873 // function. What it is an address of varies:
3874 //
John Kessenich4bf71552016-09-02 11:20:21 -06003875 // - "in" parameters not marked as "const" can be written to without modifying the calling
3876 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003877 //
3878 // - "const in" parameters can just be the r-value, as no writes need occur.
3879 //
John Kessenich4bf71552016-09-02 11:20:21 -06003880 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3881 // 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 -06003882
3883 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003884 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003885 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3886
John Kessenichfad62972017-07-18 02:35:46 -06003887 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3888 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003889
John Kessenichfad62972017-07-18 02:35:46 -06003890 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003891 for (int p = 0; p < (int)parameters.size(); ++p) {
3892 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3893 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003894 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003895 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003896 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003897 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3898 else
John Kessenich4bf71552016-09-02 11:20:21 -06003899 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003900 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003901 paramTypes.push_back(typeId);
3902 }
3903
3904 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003905 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3906 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003907 glslFunction->getName().c_str(), paramTypes,
3908 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003909 if (implicitThis)
3910 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003911
3912 // Track function to emit/call later
3913 functionMap[glslFunction->getName().c_str()] = function;
3914
3915 // Set the parameter id's
3916 for (int p = 0; p < (int)parameters.size(); ++p) {
3917 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3918 // give a name too
3919 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3920 }
3921 }
3922}
3923
3924// Process all the initializers, while skipping the functions and link objects
3925void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3926{
3927 builder.setBuildPoint(shaderEntry->getLastBlock());
3928 for (int i = 0; i < (int)initializers.size(); ++i) {
3929 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3930 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3931
3932 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003933 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003934 initializer->traverse(this);
3935 }
3936 }
3937}
3938
3939// Process all the functions, while skipping initializers.
3940void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3941{
3942 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3943 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003944 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003945 node->traverse(this);
3946 }
3947}
3948
3949void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3950{
qining25262b32016-05-06 17:25:16 -04003951 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003952 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003953 currentFunction = functionMap[node->getName().c_str()];
3954 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003955 builder.setBuildPoint(functionBlock);
3956}
3957
Rex Xu04db3f52015-09-16 11:44:02 +08003958void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003959{
Rex Xufc618912015-09-09 16:42:49 +08003960 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003961
3962 glslang::TSampler sampler = {};
3963 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003964#ifdef AMD_EXTENSIONS
3965 bool f16ShadowCompare = false;
3966#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003967 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003968 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3969 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003970#ifdef AMD_EXTENSIONS
3971 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3972#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003973 }
3974
John Kessenich140f3df2015-06-26 16:58:36 -06003975 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3976 builder.clearAccessChain();
3977 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003978
3979 // Special case l-value operands
3980 bool lvalue = false;
3981 switch (node.getOp()) {
3982 case glslang::EOpImageAtomicAdd:
3983 case glslang::EOpImageAtomicMin:
3984 case glslang::EOpImageAtomicMax:
3985 case glslang::EOpImageAtomicAnd:
3986 case glslang::EOpImageAtomicOr:
3987 case glslang::EOpImageAtomicXor:
3988 case glslang::EOpImageAtomicExchange:
3989 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003990 case glslang::EOpImageAtomicLoad:
3991 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003992 if (i == 0)
3993 lvalue = true;
3994 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003995 case glslang::EOpSparseImageLoad:
3996 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3997 lvalue = true;
3998 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003999#ifdef AMD_EXTENSIONS
4000 case glslang::EOpSparseTexture:
4001 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4002 lvalue = true;
4003 break;
4004 case glslang::EOpSparseTextureClamp:
4005 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4006 lvalue = true;
4007 break;
4008 case glslang::EOpSparseTextureLod:
4009 case glslang::EOpSparseTextureOffset:
4010 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4011 lvalue = true;
4012 break;
4013#else
Rex Xu48edadf2015-12-31 16:11:41 +08004014 case glslang::EOpSparseTexture:
4015 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4016 lvalue = true;
4017 break;
4018 case glslang::EOpSparseTextureClamp:
4019 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4020 lvalue = true;
4021 break;
4022 case glslang::EOpSparseTextureLod:
4023 case glslang::EOpSparseTextureOffset:
4024 if (i == 3)
4025 lvalue = true;
4026 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004027#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004028 case glslang::EOpSparseTextureFetch:
4029 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4030 lvalue = true;
4031 break;
4032 case glslang::EOpSparseTextureFetchOffset:
4033 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4034 lvalue = true;
4035 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004036#ifdef AMD_EXTENSIONS
4037 case glslang::EOpSparseTextureLodOffset:
4038 case glslang::EOpSparseTextureGrad:
4039 case glslang::EOpSparseTextureOffsetClamp:
4040 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4041 lvalue = true;
4042 break;
4043 case glslang::EOpSparseTextureGradOffset:
4044 case glslang::EOpSparseTextureGradClamp:
4045 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4046 lvalue = true;
4047 break;
4048 case glslang::EOpSparseTextureGradOffsetClamp:
4049 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4050 lvalue = true;
4051 break;
4052#else
Rex Xu48edadf2015-12-31 16:11:41 +08004053 case glslang::EOpSparseTextureLodOffset:
4054 case glslang::EOpSparseTextureGrad:
4055 case glslang::EOpSparseTextureOffsetClamp:
4056 if (i == 4)
4057 lvalue = true;
4058 break;
4059 case glslang::EOpSparseTextureGradOffset:
4060 case glslang::EOpSparseTextureGradClamp:
4061 if (i == 5)
4062 lvalue = true;
4063 break;
4064 case glslang::EOpSparseTextureGradOffsetClamp:
4065 if (i == 6)
4066 lvalue = true;
4067 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004068#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004069 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004070 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4071 lvalue = true;
4072 break;
4073 case glslang::EOpSparseTextureGatherOffset:
4074 case glslang::EOpSparseTextureGatherOffsets:
4075 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4076 lvalue = true;
4077 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004078#ifdef AMD_EXTENSIONS
4079 case glslang::EOpSparseTextureGatherLod:
4080 if (i == 3)
4081 lvalue = true;
4082 break;
4083 case glslang::EOpSparseTextureGatherLodOffset:
4084 case glslang::EOpSparseTextureGatherLodOffsets:
4085 if (i == 4)
4086 lvalue = true;
4087 break;
Rex Xu129799a2017-07-05 17:23:28 +08004088 case glslang::EOpSparseImageLoadLod:
4089 if (i == 3)
4090 lvalue = true;
4091 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004092#endif
Chao Chen3a137962018-09-19 11:41:27 -07004093#ifdef NV_EXTENSIONS
4094 case glslang::EOpImageSampleFootprintNV:
4095 if (i == 4)
4096 lvalue = true;
4097 break;
4098 case glslang::EOpImageSampleFootprintClampNV:
4099 case glslang::EOpImageSampleFootprintLodNV:
4100 if (i == 5)
4101 lvalue = true;
4102 break;
4103 case glslang::EOpImageSampleFootprintGradNV:
4104 if (i == 6)
4105 lvalue = true;
4106 break;
4107 case glslang::EOpImageSampleFootprintGradClampNV:
4108 if (i == 7)
4109 lvalue = true;
4110 break;
4111#endif
Rex Xufc618912015-09-09 16:42:49 +08004112 default:
4113 break;
4114 }
4115
Rex Xu6b86d492015-09-16 17:48:22 +08004116 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004117 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004118 else
John Kessenich32cfd492016-02-02 12:37:46 -07004119 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004120 }
4121}
4122
John Kessenichfc51d282015-08-19 13:34:18 -06004123void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004124{
John Kessenichfc51d282015-08-19 13:34:18 -06004125 builder.clearAccessChain();
4126 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004127 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004128}
John Kessenich140f3df2015-06-26 16:58:36 -06004129
John Kessenichfc51d282015-08-19 13:34:18 -06004130spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4131{
John Kesseniche485c7a2017-05-31 18:50:53 -06004132 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004133 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004134
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004135 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004136
John Kessenichfc51d282015-08-19 13:34:18 -06004137 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004138
4139 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4140 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4141 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004142#ifdef AMD_EXTENSIONS
4143 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4144 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4145 : false;
4146#endif
4147
John Kessenichfc51d282015-08-19 13:34:18 -06004148 std::vector<spv::Id> arguments;
4149 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004150 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004151 else
4152 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004153 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004154
4155 spv::Builder::TextureParameters params = { };
4156 params.sampler = arguments[0];
4157
Rex Xu04db3f52015-09-16 11:44:02 +08004158 glslang::TCrackedTextureOp cracked;
4159 node->crackTexture(sampler, cracked);
4160
amhagan05506bb2017-06-13 16:53:02 -04004161 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004162
John Kessenichfc51d282015-08-19 13:34:18 -06004163 // Check for queries
4164 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004165 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4166 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004167 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004168
John Kessenichfc51d282015-08-19 13:34:18 -06004169 switch (node->getOp()) {
4170 case glslang::EOpImageQuerySize:
4171 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004172 if (arguments.size() > 1) {
4173 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004174 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004175 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004176 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004177 case glslang::EOpImageQuerySamples:
4178 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004179 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004180 case glslang::EOpTextureQueryLod:
4181 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004182 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004183 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004184 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004185 case glslang::EOpSparseTexelsResident:
4186 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004187 default:
4188 assert(0);
4189 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004190 }
John Kessenich140f3df2015-06-26 16:58:36 -06004191 }
4192
LoopDawg4425f242018-02-18 11:40:01 -07004193 int components = node->getType().getVectorSize();
4194
4195 if (node->getOp() == glslang::EOpTextureFetch) {
4196 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4197 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4198 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4199 // here around e.g. which ones return scalars or other types.
4200 components = 4;
4201 }
4202
4203 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4204
4205 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4206
Rex Xufc618912015-09-09 16:42:49 +08004207 // Check for image functions other than queries
4208 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004209 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004210 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004211 spv::IdImmediate image = { true, *(opIt++) };
4212 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004213
4214 // Handle subpass operations
4215 // TODO: GLSL should change to have the "MS" only on the type rather than the
4216 // built-in function.
4217 if (cracked.subpass) {
4218 // add on the (0,0) coordinate
4219 spv::Id zero = builder.makeIntConstant(0);
4220 std::vector<spv::Id> comps;
4221 comps.push_back(zero);
4222 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004223 spv::IdImmediate coord = { true,
4224 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4225 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004226 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004227 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4228 operands.push_back(imageOperands);
4229 spv::IdImmediate imageOperand = { true, *(opIt++) };
4230 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004231 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004232 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4233 builder.setPrecision(result, precision);
4234 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004235 }
4236
John Kessenich149afc32018-08-14 13:31:43 -06004237 spv::IdImmediate coord = { true, *(opIt++) };
4238 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004239#ifdef AMD_EXTENSIONS
4240 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4241#else
John Kessenich56bab042015-09-16 10:54:31 -06004242 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004243#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004244 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004245 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004246 mask = mask | spv::ImageOperandsSampleMask;
4247 }
Rex Xu129799a2017-07-05 17:23:28 +08004248#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004249 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004250 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4251 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004252 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004253 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004254#endif
4255 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4256 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4257 if (mask) {
4258 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4259 operands.push_back(imageOperands);
4260 }
4261 if (mask & spv::ImageOperandsSampleMask) {
4262 spv::IdImmediate imageOperand = { true, *opIt++ };
4263 operands.push_back(imageOperand);
4264 }
4265#ifdef AMD_EXTENSIONS
4266 if (mask & spv::ImageOperandsLodMask) {
4267 spv::IdImmediate imageOperand = { true, *opIt++ };
4268 operands.push_back(imageOperand);
4269 }
4270#endif
4271 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4272 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4273 operands.push_back(imageOperand);
4274 }
4275
John Kessenich149afc32018-08-14 13:31:43 -06004276 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004277 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004278
John Kessenich149afc32018-08-14 13:31:43 -06004279 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004280 builder.setPrecision(result[0], precision);
4281
4282 // If needed, add a conversion constructor to the proper size.
4283 if (components != node->getType().getVectorSize())
4284 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4285
4286 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004287#ifdef AMD_EXTENSIONS
4288 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4289#else
John Kessenich56bab042015-09-16 10:54:31 -06004290 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004291#endif
Rex Xu129799a2017-07-05 17:23:28 +08004292
Jeff Bolz36831c92018-09-05 10:11:41 -05004293 // Push the texel value before the operands
4294#ifdef AMD_EXTENSIONS
4295 if (sampler.ms || cracked.lod) {
4296#else
4297 if (sampler.ms) {
4298#endif
John Kessenich149afc32018-08-14 13:31:43 -06004299 spv::IdImmediate texel = { true, *(opIt + 1) };
4300 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004301 } else {
4302 spv::IdImmediate texel = { true, *opIt };
4303 operands.push_back(texel);
4304 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004305
4306 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4307 if (sampler.ms) {
4308 mask = mask | spv::ImageOperandsSampleMask;
4309 }
4310#ifdef AMD_EXTENSIONS
4311 if (cracked.lod) {
4312 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4313 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4314 mask = mask | spv::ImageOperandsLodMask;
4315 }
4316#endif
4317 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4318 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4319 if (mask) {
4320 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4321 operands.push_back(imageOperands);
4322 }
4323 if (mask & spv::ImageOperandsSampleMask) {
4324 spv::IdImmediate imageOperand = { true, *opIt++ };
4325 operands.push_back(imageOperand);
4326 }
4327#ifdef AMD_EXTENSIONS
4328 if (mask & spv::ImageOperandsLodMask) {
4329 spv::IdImmediate imageOperand = { true, *opIt++ };
4330 operands.push_back(imageOperand);
4331 }
4332#endif
4333 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4334 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4335 operands.push_back(imageOperand);
4336 }
4337
John Kessenich56bab042015-09-16 10:54:31 -06004338 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004339 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004340 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004341 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004342#ifdef AMD_EXTENSIONS
4343 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4344#else
Rex Xu5eafa472016-02-19 22:24:03 +08004345 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004346#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004347 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004348 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004349 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4350
Jeff Bolz36831c92018-09-05 10:11:41 -05004351 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004352 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004353 mask = mask | spv::ImageOperandsSampleMask;
4354 }
Rex Xu129799a2017-07-05 17:23:28 +08004355#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004356 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004357 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4358 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4359
Jeff Bolz36831c92018-09-05 10:11:41 -05004360 mask = mask | spv::ImageOperandsLodMask;
4361 }
4362#endif
4363 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4364 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4365 if (mask) {
4366 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004367 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004368 }
4369 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004370 spv::IdImmediate imageOperand = { true, *opIt++ };
4371 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004372 }
4373#ifdef AMD_EXTENSIONS
4374 if (mask & spv::ImageOperandsLodMask) {
4375 spv::IdImmediate imageOperand = { true, *opIt++ };
4376 operands.push_back(imageOperand);
4377 }
Rex Xu129799a2017-07-05 17:23:28 +08004378#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004379 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4380 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4381 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004382 }
4383
4384 // Create the return type that was a special structure
4385 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004386 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004387 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4388 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4389
4390 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4391
4392 // Decode the return type
4393 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4394 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004395 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004396 // Process image atomic operations
4397
4398 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4399 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004400 // For non-MS, the sample value should be 0
4401 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4402 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004403
Jeff Bolz36831c92018-09-05 10:11:41 -05004404 spv::Id resultTypeId;
4405 // imageAtomicStore has a void return type so base the pointer type on
4406 // the type of the value operand.
4407 if (node->getOp() == glslang::EOpImageAtomicStore) {
4408 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4409 } else {
4410 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4411 }
John Kessenich56bab042015-09-16 10:54:31 -06004412 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004413
4414 std::vector<spv::Id> operands;
4415 operands.push_back(pointer);
4416 for (; opIt != arguments.end(); ++opIt)
4417 operands.push_back(*opIt);
4418
John Kessenich8c8505c2016-07-26 12:50:38 -06004419 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004420 }
4421 }
4422
amhagan05506bb2017-06-13 16:53:02 -04004423#ifdef AMD_EXTENSIONS
4424 // Check for fragment mask functions other than queries
4425 if (cracked.fragMask) {
4426 assert(sampler.ms);
4427
4428 auto opIt = arguments.begin();
4429 std::vector<spv::Id> operands;
4430
4431 // Extract the image if necessary
4432 if (builder.isSampledImage(params.sampler))
4433 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4434
4435 operands.push_back(params.sampler);
4436 ++opIt;
4437
4438 if (sampler.isSubpass()) {
4439 // add on the (0,0) coordinate
4440 spv::Id zero = builder.makeIntConstant(0);
4441 std::vector<spv::Id> comps;
4442 comps.push_back(zero);
4443 comps.push_back(zero);
4444 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4445 }
4446
4447 for (; opIt != arguments.end(); ++opIt)
4448 operands.push_back(*opIt);
4449
4450 spv::Op fragMaskOp = spv::OpNop;
4451 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4452 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4453 else if (node->getOp() == glslang::EOpFragmentFetch)
4454 fragMaskOp = spv::OpFragmentFetchAMD;
4455
4456 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4457 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4458 return builder.createOp(fragMaskOp, resultType(), operands);
4459 }
4460#endif
4461
Rex Xufc618912015-09-09 16:42:49 +08004462 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004463 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004464#ifdef NV_EXTENSIONS
4465 bool imageFootprint = node->isImageFootprint();
4466#endif
4467
Rex Xu71519fe2015-11-11 15:35:47 +08004468 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4469
John Kessenichfc51d282015-08-19 13:34:18 -06004470 // check for bias argument
4471 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004472#ifdef AMD_EXTENSIONS
4473 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4474#else
Rex Xu71519fe2015-11-11 15:35:47 +08004475 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004476#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004477 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004478#ifdef AMD_EXTENSIONS
4479 if (cracked.gather)
4480 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004481
4482 if (f16ShadowCompare)
4483 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004484#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004485 if (cracked.offset)
4486 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004487#ifdef AMD_EXTENSIONS
4488 else if (cracked.offsets)
4489 ++nonBiasArgCount;
4490#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004491 if (cracked.grad)
4492 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004493 if (cracked.lodClamp)
4494 ++nonBiasArgCount;
4495 if (sparse)
4496 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004497#ifdef NV_EXTENSIONS
4498 if (imageFootprint)
4499 //Following three extra arguments
4500 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4501 nonBiasArgCount += 3;
4502#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004503 if ((int)arguments.size() > nonBiasArgCount)
4504 bias = true;
4505 }
4506
John Kessenicha5c33d62016-06-02 23:45:21 -06004507 // See if the sampler param should really be just the SPV image part
4508 if (cracked.fetch) {
4509 // a fetch needs to have the image extracted first
4510 if (builder.isSampledImage(params.sampler))
4511 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4512 }
4513
Rex Xu225e0fc2016-11-17 17:47:59 +08004514#ifdef AMD_EXTENSIONS
4515 if (cracked.gather) {
4516 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4517 if (bias || cracked.lod ||
4518 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4519 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004520 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004521 }
4522 }
4523#endif
4524
John Kessenichfc51d282015-08-19 13:34:18 -06004525 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004526
John Kessenichfc51d282015-08-19 13:34:18 -06004527 params.coords = arguments[1];
4528 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004529 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004530
4531 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004532#ifdef AMD_EXTENSIONS
4533 if (cubeCompare || f16ShadowCompare) {
4534#else
Rex Xu48edadf2015-12-31 16:11:41 +08004535 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004536#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004537 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004538 ++extraArgs;
4539 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004540 params.Dref = arguments[2];
4541 ++extraArgs;
4542 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004543 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004544 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004545 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004546 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004547 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004548 dRefComp = builder.getNumComponents(params.coords) - 1;
4549 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004550 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4551 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004552
4553 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004554 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004555 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004556 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004557 } else if (glslangIntermediate->getStage() != EShLangFragment
4558#ifdef NV_EXTENSIONS
4559 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4560 && !(glslangIntermediate->getStage() == EShLangCompute &&
4561 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4562#endif
4563 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004564 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4565 noImplicitLod = true;
4566 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004567
4568 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004569 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004570 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004571 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004572 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004573
4574 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004575 if (cracked.grad) {
4576 params.gradX = arguments[2 + extraArgs];
4577 params.gradY = arguments[3 + extraArgs];
4578 extraArgs += 2;
4579 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004580
4581 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004582 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004583 params.offset = arguments[2 + extraArgs];
4584 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004585 } else if (cracked.offsets) {
4586 params.offsets = arguments[2 + extraArgs];
4587 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004588 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004589
4590 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004591 if (cracked.lodClamp) {
4592 params.lodClamp = arguments[2 + extraArgs];
4593 ++extraArgs;
4594 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004595 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004596 if (sparse) {
4597 params.texelOut = arguments[2 + extraArgs];
4598 ++extraArgs;
4599 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004600
John Kessenich76d4dfc2016-06-16 12:43:23 -06004601 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004602 if (cracked.gather && ! sampler.shadow) {
4603 // default component is 0, if missing, otherwise an argument
4604 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004605 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004606 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004607 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004608 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004609 }
Chao Chen3a137962018-09-19 11:41:27 -07004610#ifdef NV_EXTENSIONS
4611 spv::Id resultStruct = spv::NoResult;
4612 if (imageFootprint) {
4613 //Following three extra arguments
4614 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4615 params.granularity = arguments[2 + extraArgs];
4616 params.coarse = arguments[3 + extraArgs];
4617 resultStruct = arguments[4 + extraArgs];
4618 extraArgs += 3;
4619 }
4620#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004621 // bias
4622 if (bias) {
4623 params.bias = arguments[2 + extraArgs];
4624 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004625 }
John Kessenichfc51d282015-08-19 13:34:18 -06004626
Chao Chen3a137962018-09-19 11:41:27 -07004627#ifdef NV_EXTENSIONS
4628 if (imageFootprint) {
4629 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4630 builder.addCapability(spv::CapabilityImageFootprintNV);
4631
4632
4633 //resultStructType(OpenGL type) contains 5 elements:
4634 //struct gl_TextureFootprint2DNV {
4635 // uvec2 anchor;
4636 // uvec2 offset;
4637 // uvec2 mask;
4638 // uint lod;
4639 // uint granularity;
4640 //};
4641 //or
4642 //struct gl_TextureFootprint3DNV {
4643 // uvec3 anchor;
4644 // uvec3 offset;
4645 // uvec2 mask;
4646 // uint lod;
4647 // uint granularity;
4648 //};
4649 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4650 assert(builder.isStructType(resultStructType));
4651
4652 //resType (SPIR-V type) contains 6 elements:
4653 //Member 0 must be a Boolean type scalar(LOD),
4654 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4655 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4656 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4657 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4658 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4659 std::vector<spv::Id> members;
4660 members.push_back(resultType());
4661 for (int i = 0; i < 5; i++) {
4662 members.push_back(builder.getContainedTypeId(resultStructType, i));
4663 }
4664 spv::Id resType = builder.makeStructType(members, "ResType");
4665
4666 //call ImageFootprintNV
4667 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4668
4669 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4670 for (int i = 0; i < 5; i++) {
4671 builder.clearAccessChain();
4672 builder.setAccessChainLValue(resultStruct);
4673
4674 //Accessing to a struct we created, no coherent flag is set
4675 spv::Builder::AccessChain::CoherentFlags flags;
4676 flags.clear();
4677
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004678 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004679 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4680 }
4681 return builder.createCompositeExtract(res, resultType(), 0);
4682 }
4683#endif
4684
John Kessenich65336482016-06-16 14:06:26 -06004685 // projective component (might not to move)
4686 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4687 // are divided by the last component of P."
4688 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4689 // unused components will appear after all used components."
4690 if (cracked.proj) {
4691 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4692 int projTargetComp;
4693 switch (sampler.dim) {
4694 case glslang::Esd1D: projTargetComp = 1; break;
4695 case glslang::Esd2D: projTargetComp = 2; break;
4696 case glslang::EsdRect: projTargetComp = 2; break;
4697 default: projTargetComp = projSourceComp; break;
4698 }
4699 // copy the projective coordinate if we have to
4700 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004701 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004702 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4703 projSourceComp);
4704 params.coords = builder.createCompositeInsert(projComp, params.coords,
4705 builder.getTypeId(params.coords), projTargetComp);
4706 }
4707 }
4708
Jeff Bolz36831c92018-09-05 10:11:41 -05004709 // nonprivate
4710 if (imageType.getQualifier().nonprivate) {
4711 params.nonprivate = true;
4712 }
4713
4714 // volatile
4715 if (imageType.getQualifier().volatil) {
4716 params.volatil = true;
4717 }
4718
St0fFa1184dd2018-04-09 21:08:14 +02004719 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004720 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004721 );
LoopDawg4425f242018-02-18 11:40:01 -07004722
4723 if (components != node->getType().getVectorSize())
4724 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4725
4726 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004727}
4728
4729spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4730{
4731 // Grab the function's pointer from the previously created function
4732 spv::Function* function = functionMap[node->getName().c_str()];
4733 if (! function)
4734 return 0;
4735
4736 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4737 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4738
4739 // See comments in makeFunctions() for details about the semantics for parameter passing.
4740 //
4741 // These imply we need a four step process:
4742 // 1. Evaluate the arguments
4743 // 2. Allocate and make copies of in, out, and inout arguments
4744 // 3. Make the call
4745 // 4. Copy back the results
4746
John Kessenichd3ed90b2018-05-04 11:43:03 -06004747 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004748 std::vector<spv::Builder::AccessChain> lValues;
4749 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004750 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004751 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004752 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004753 // build l-value
4754 builder.clearAccessChain();
4755 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004756 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004757 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004758 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004759 // save l-value
4760 lValues.push_back(builder.getAccessChain());
4761 } else {
4762 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004763 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004764 }
4765 }
4766
4767 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4768 // copy the original into that space.
4769 //
4770 // Also, build up the list of actual arguments to pass in for the call
4771 int lValueCount = 0;
4772 int rValueCount = 0;
4773 std::vector<spv::Id> spvArgs;
4774 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4775 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004776 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004777 builder.setAccessChain(lValues[lValueCount]);
4778 arg = builder.accessChainGetLValue();
4779 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004780 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004781 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004782 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004783 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4784 // need to copy the input into output space
4785 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004786 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004787 builder.clearAccessChain();
4788 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004789 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004790 }
4791 ++lValueCount;
4792 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004793 // process r-value, which involves a copy for a type mismatch
4794 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4795 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4796 builder.clearAccessChain();
4797 builder.setAccessChainLValue(argCopy);
4798 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4799 arg = builder.createLoad(argCopy);
4800 } else
4801 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004802 ++rValueCount;
4803 }
4804 spvArgs.push_back(arg);
4805 }
4806
4807 // 3. Make the call.
4808 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004809 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004810
4811 // 4. Copy back out an "out" arguments.
4812 lValueCount = 0;
4813 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004814 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004815 ++lValueCount;
4816 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004817 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4818 spv::Id copy = builder.createLoad(spvArgs[a]);
4819 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004820 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004821 }
4822 ++lValueCount;
4823 }
4824 }
4825
4826 return result;
4827}
4828
4829// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004830spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004831 spv::Id typeId, spv::Id left, spv::Id right,
4832 glslang::TBasicType typeProxy, bool reduceComparison)
4833{
John Kessenich66011cb2018-03-06 16:12:04 -07004834 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4835 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004836 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004837
4838 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004839 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004840 bool comparison = false;
4841
4842 switch (op) {
4843 case glslang::EOpAdd:
4844 case glslang::EOpAddAssign:
4845 if (isFloat)
4846 binOp = spv::OpFAdd;
4847 else
4848 binOp = spv::OpIAdd;
4849 break;
4850 case glslang::EOpSub:
4851 case glslang::EOpSubAssign:
4852 if (isFloat)
4853 binOp = spv::OpFSub;
4854 else
4855 binOp = spv::OpISub;
4856 break;
4857 case glslang::EOpMul:
4858 case glslang::EOpMulAssign:
4859 if (isFloat)
4860 binOp = spv::OpFMul;
4861 else
4862 binOp = spv::OpIMul;
4863 break;
4864 case glslang::EOpVectorTimesScalar:
4865 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004866 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004867 if (builder.isVector(right))
4868 std::swap(left, right);
4869 assert(builder.isScalar(right));
4870 needMatchingVectors = false;
4871 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004872 } else if (isFloat)
4873 binOp = spv::OpFMul;
4874 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004875 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004876 break;
4877 case glslang::EOpVectorTimesMatrix:
4878 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004879 binOp = spv::OpVectorTimesMatrix;
4880 break;
4881 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004882 binOp = spv::OpMatrixTimesVector;
4883 break;
4884 case glslang::EOpMatrixTimesScalar:
4885 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004886 binOp = spv::OpMatrixTimesScalar;
4887 break;
4888 case glslang::EOpMatrixTimesMatrix:
4889 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004890 binOp = spv::OpMatrixTimesMatrix;
4891 break;
4892 case glslang::EOpOuterProduct:
4893 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004894 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004895 break;
4896
4897 case glslang::EOpDiv:
4898 case glslang::EOpDivAssign:
4899 if (isFloat)
4900 binOp = spv::OpFDiv;
4901 else if (isUnsigned)
4902 binOp = spv::OpUDiv;
4903 else
4904 binOp = spv::OpSDiv;
4905 break;
4906 case glslang::EOpMod:
4907 case glslang::EOpModAssign:
4908 if (isFloat)
4909 binOp = spv::OpFMod;
4910 else if (isUnsigned)
4911 binOp = spv::OpUMod;
4912 else
4913 binOp = spv::OpSMod;
4914 break;
4915 case glslang::EOpRightShift:
4916 case glslang::EOpRightShiftAssign:
4917 if (isUnsigned)
4918 binOp = spv::OpShiftRightLogical;
4919 else
4920 binOp = spv::OpShiftRightArithmetic;
4921 break;
4922 case glslang::EOpLeftShift:
4923 case glslang::EOpLeftShiftAssign:
4924 binOp = spv::OpShiftLeftLogical;
4925 break;
4926 case glslang::EOpAnd:
4927 case glslang::EOpAndAssign:
4928 binOp = spv::OpBitwiseAnd;
4929 break;
4930 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004931 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004932 binOp = spv::OpLogicalAnd;
4933 break;
4934 case glslang::EOpInclusiveOr:
4935 case glslang::EOpInclusiveOrAssign:
4936 binOp = spv::OpBitwiseOr;
4937 break;
4938 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004939 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004940 binOp = spv::OpLogicalOr;
4941 break;
4942 case glslang::EOpExclusiveOr:
4943 case glslang::EOpExclusiveOrAssign:
4944 binOp = spv::OpBitwiseXor;
4945 break;
4946 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004947 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004948 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004949 break;
4950
4951 case glslang::EOpLessThan:
4952 case glslang::EOpGreaterThan:
4953 case glslang::EOpLessThanEqual:
4954 case glslang::EOpGreaterThanEqual:
4955 case glslang::EOpEqual:
4956 case glslang::EOpNotEqual:
4957 case glslang::EOpVectorEqual:
4958 case glslang::EOpVectorNotEqual:
4959 comparison = true;
4960 break;
4961 default:
4962 break;
4963 }
4964
John Kessenich7c1aa102015-10-15 13:29:11 -06004965 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004966 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004967 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004968 if (builder.isMatrix(left) || builder.isMatrix(right) ||
4969 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004970 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004971
4972 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004973 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004974 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004975
qining25262b32016-05-06 17:25:16 -04004976 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004977 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004978 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004979 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004980 }
4981
4982 if (! comparison)
4983 return 0;
4984
John Kessenich7c1aa102015-10-15 13:29:11 -06004985 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004986
John Kessenich4583b612016-08-07 19:14:22 -06004987 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004988 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4989 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004990 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004991 return result;
4992 }
John Kessenich140f3df2015-06-26 16:58:36 -06004993
4994 switch (op) {
4995 case glslang::EOpLessThan:
4996 if (isFloat)
4997 binOp = spv::OpFOrdLessThan;
4998 else if (isUnsigned)
4999 binOp = spv::OpULessThan;
5000 else
5001 binOp = spv::OpSLessThan;
5002 break;
5003 case glslang::EOpGreaterThan:
5004 if (isFloat)
5005 binOp = spv::OpFOrdGreaterThan;
5006 else if (isUnsigned)
5007 binOp = spv::OpUGreaterThan;
5008 else
5009 binOp = spv::OpSGreaterThan;
5010 break;
5011 case glslang::EOpLessThanEqual:
5012 if (isFloat)
5013 binOp = spv::OpFOrdLessThanEqual;
5014 else if (isUnsigned)
5015 binOp = spv::OpULessThanEqual;
5016 else
5017 binOp = spv::OpSLessThanEqual;
5018 break;
5019 case glslang::EOpGreaterThanEqual:
5020 if (isFloat)
5021 binOp = spv::OpFOrdGreaterThanEqual;
5022 else if (isUnsigned)
5023 binOp = spv::OpUGreaterThanEqual;
5024 else
5025 binOp = spv::OpSGreaterThanEqual;
5026 break;
5027 case glslang::EOpEqual:
5028 case glslang::EOpVectorEqual:
5029 if (isFloat)
5030 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005031 else if (isBool)
5032 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005033 else
5034 binOp = spv::OpIEqual;
5035 break;
5036 case glslang::EOpNotEqual:
5037 case glslang::EOpVectorNotEqual:
5038 if (isFloat)
5039 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005040 else if (isBool)
5041 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005042 else
5043 binOp = spv::OpINotEqual;
5044 break;
5045 default:
5046 break;
5047 }
5048
qining25262b32016-05-06 17:25:16 -04005049 if (binOp != spv::OpNop) {
5050 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005051 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005052 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005053 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005054 }
John Kessenich140f3df2015-06-26 16:58:36 -06005055
5056 return 0;
5057}
5058
John Kessenich04bb8a02015-12-12 12:28:14 -07005059//
5060// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5061// These can be any of:
5062//
5063// matrix * scalar
5064// scalar * matrix
5065// matrix * matrix linear algebraic
5066// matrix * vector
5067// vector * matrix
5068// matrix * matrix componentwise
5069// matrix op matrix op in {+, -, /}
5070// matrix op scalar op in {+, -, /}
5071// scalar op matrix op in {+, -, /}
5072//
John Kessenichead86222018-03-28 18:01:20 -06005073spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5074 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005075{
5076 bool firstClass = true;
5077
5078 // First, handle first-class matrix operations (* and matrix/scalar)
5079 switch (op) {
5080 case spv::OpFDiv:
5081 if (builder.isMatrix(left) && builder.isScalar(right)) {
5082 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005083 spv::Id resultType = builder.getTypeId(right);
5084 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005085 op = spv::OpMatrixTimesScalar;
5086 } else
5087 firstClass = false;
5088 break;
5089 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005090 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005091 std::swap(left, right);
5092 assert(builder.isScalar(right));
5093 break;
5094 case spv::OpVectorTimesMatrix:
5095 assert(builder.isVector(left));
5096 assert(builder.isMatrix(right));
5097 break;
5098 case spv::OpMatrixTimesVector:
5099 assert(builder.isMatrix(left));
5100 assert(builder.isVector(right));
5101 break;
5102 case spv::OpMatrixTimesMatrix:
5103 assert(builder.isMatrix(left));
5104 assert(builder.isMatrix(right));
5105 break;
5106 default:
5107 firstClass = false;
5108 break;
5109 }
5110
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005111 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5112 firstClass = true;
5113
qining25262b32016-05-06 17:25:16 -04005114 if (firstClass) {
5115 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005116 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005117 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005118 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005119 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005120
LoopDawg592860c2016-06-09 08:57:35 -06005121 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005122 // The result type of all of them is the same type as the (a) matrix operand.
5123 // The algorithm is to:
5124 // - break the matrix(es) into vectors
5125 // - smear any scalar to a vector
5126 // - do vector operations
5127 // - make a matrix out the vector results
5128 switch (op) {
5129 case spv::OpFAdd:
5130 case spv::OpFSub:
5131 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005132 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005133 case spv::OpFMul:
5134 {
5135 // one time set up...
5136 bool leftMat = builder.isMatrix(left);
5137 bool rightMat = builder.isMatrix(right);
5138 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5139 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5140 spv::Id scalarType = builder.getScalarTypeId(typeId);
5141 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5142 std::vector<spv::Id> results;
5143 spv::Id smearVec = spv::NoResult;
5144 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005145 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005146 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005147 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005148
5149 // do each vector op
5150 for (unsigned int c = 0; c < numCols; ++c) {
5151 std::vector<unsigned int> indexes;
5152 indexes.push_back(c);
5153 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5154 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005155 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005156 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005157 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005158 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005159 }
5160
5161 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005162 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005163 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005164 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005165 }
5166 default:
5167 assert(0);
5168 return spv::NoResult;
5169 }
5170}
5171
John Kessenichead86222018-03-28 18:01:20 -06005172spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5173 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005174{
5175 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005176 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005177 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005178 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5179 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005180
5181 switch (op) {
5182 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005183 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005184 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005185 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005186 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005187 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005188 unaryOp = spv::OpSNegate;
5189 break;
5190
5191 case glslang::EOpLogicalNot:
5192 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005193 unaryOp = spv::OpLogicalNot;
5194 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005195 case glslang::EOpBitwiseNot:
5196 unaryOp = spv::OpNot;
5197 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005198
John Kessenich140f3df2015-06-26 16:58:36 -06005199 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005200 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005201 break;
5202 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005203 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005204 break;
5205 case glslang::EOpTranspose:
5206 unaryOp = spv::OpTranspose;
5207 break;
5208
5209 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005210 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005211 break;
5212 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005213 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005214 break;
5215 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005216 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005217 break;
5218 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005219 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005220 break;
5221 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005222 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 break;
5224 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005225 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 break;
5227 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005228 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005229 break;
5230 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233
5234 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005235 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005236 break;
5237 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005238 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005239 break;
5240 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005241 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005242 break;
5243 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005244 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005245 break;
5246 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005247 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 break;
5249 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005250 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
5252
5253 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005254 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005255 break;
5256 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005257 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005258 break;
5259
5260 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005261 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005262 break;
5263 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005264 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005265 break;
5266 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005267 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005268 break;
5269 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005270 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005273 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
5275 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
5278
5279 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005280 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005281 break;
5282 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005283 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005284 break;
5285 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005286 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005287 break;
5288 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005289 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 break;
5291 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005292 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
5294 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005295 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005296 break;
5297
5298 case glslang::EOpIsNan:
5299 unaryOp = spv::OpIsNan;
5300 break;
5301 case glslang::EOpIsInf:
5302 unaryOp = spv::OpIsInf;
5303 break;
LoopDawg592860c2016-06-09 08:57:35 -06005304 case glslang::EOpIsFinite:
5305 unaryOp = spv::OpIsFinite;
5306 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005307
Rex Xucbc426e2015-12-15 16:03:10 +08005308 case glslang::EOpFloatBitsToInt:
5309 case glslang::EOpFloatBitsToUint:
5310 case glslang::EOpIntBitsToFloat:
5311 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005312 case glslang::EOpDoubleBitsToInt64:
5313 case glslang::EOpDoubleBitsToUint64:
5314 case glslang::EOpInt64BitsToDouble:
5315 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005316 case glslang::EOpFloat16BitsToInt16:
5317 case glslang::EOpFloat16BitsToUint16:
5318 case glslang::EOpInt16BitsToFloat16:
5319 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005320 unaryOp = spv::OpBitcast;
5321 break;
5322
John Kessenich140f3df2015-06-26 16:58:36 -06005323 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005324 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005325 break;
5326 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005327 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005328 break;
5329 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005330 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005331 break;
5332 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005333 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005334 break;
5335 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005336 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005337 break;
5338 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005339 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005341 case glslang::EOpPackSnorm4x8:
5342 libCall = spv::GLSLstd450PackSnorm4x8;
5343 break;
5344 case glslang::EOpUnpackSnorm4x8:
5345 libCall = spv::GLSLstd450UnpackSnorm4x8;
5346 break;
5347 case glslang::EOpPackUnorm4x8:
5348 libCall = spv::GLSLstd450PackUnorm4x8;
5349 break;
5350 case glslang::EOpUnpackUnorm4x8:
5351 libCall = spv::GLSLstd450UnpackUnorm4x8;
5352 break;
5353 case glslang::EOpPackDouble2x32:
5354 libCall = spv::GLSLstd450PackDouble2x32;
5355 break;
5356 case glslang::EOpUnpackDouble2x32:
5357 libCall = spv::GLSLstd450UnpackDouble2x32;
5358 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005359
Rex Xu8ff43de2016-04-22 16:51:45 +08005360 case glslang::EOpPackInt2x32:
5361 case glslang::EOpUnpackInt2x32:
5362 case glslang::EOpPackUint2x32:
5363 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005364 case glslang::EOpPack16:
5365 case glslang::EOpPack32:
5366 case glslang::EOpPack64:
5367 case glslang::EOpUnpack32:
5368 case glslang::EOpUnpack16:
5369 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005370 case glslang::EOpPackInt2x16:
5371 case glslang::EOpUnpackInt2x16:
5372 case glslang::EOpPackUint2x16:
5373 case glslang::EOpUnpackUint2x16:
5374 case glslang::EOpPackInt4x16:
5375 case glslang::EOpUnpackInt4x16:
5376 case glslang::EOpPackUint4x16:
5377 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005378 case glslang::EOpPackFloat2x16:
5379 case glslang::EOpUnpackFloat2x16:
5380 unaryOp = spv::OpBitcast;
5381 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005382
John Kessenich140f3df2015-06-26 16:58:36 -06005383 case glslang::EOpDPdx:
5384 unaryOp = spv::OpDPdx;
5385 break;
5386 case glslang::EOpDPdy:
5387 unaryOp = spv::OpDPdy;
5388 break;
5389 case glslang::EOpFwidth:
5390 unaryOp = spv::OpFwidth;
5391 break;
5392 case glslang::EOpDPdxFine:
5393 unaryOp = spv::OpDPdxFine;
5394 break;
5395 case glslang::EOpDPdyFine:
5396 unaryOp = spv::OpDPdyFine;
5397 break;
5398 case glslang::EOpFwidthFine:
5399 unaryOp = spv::OpFwidthFine;
5400 break;
5401 case glslang::EOpDPdxCoarse:
5402 unaryOp = spv::OpDPdxCoarse;
5403 break;
5404 case glslang::EOpDPdyCoarse:
5405 unaryOp = spv::OpDPdyCoarse;
5406 break;
5407 case glslang::EOpFwidthCoarse:
5408 unaryOp = spv::OpFwidthCoarse;
5409 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005410 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005411#ifdef AMD_EXTENSIONS
5412 if (typeProxy == glslang::EbtFloat16)
5413 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5414#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005415 libCall = spv::GLSLstd450InterpolateAtCentroid;
5416 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005417 case glslang::EOpAny:
5418 unaryOp = spv::OpAny;
5419 break;
5420 case glslang::EOpAll:
5421 unaryOp = spv::OpAll;
5422 break;
5423
5424 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005425 if (isFloat)
5426 libCall = spv::GLSLstd450FAbs;
5427 else
5428 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005429 break;
5430 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005431 if (isFloat)
5432 libCall = spv::GLSLstd450FSign;
5433 else
5434 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005435 break;
5436
John Kessenichfc51d282015-08-19 13:34:18 -06005437 case glslang::EOpAtomicCounterIncrement:
5438 case glslang::EOpAtomicCounterDecrement:
5439 case glslang::EOpAtomicCounter:
5440 {
5441 // Handle all of the atomics in one place, in createAtomicOperation()
5442 std::vector<spv::Id> operands;
5443 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005444 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005445 }
5446
John Kessenichfc51d282015-08-19 13:34:18 -06005447 case glslang::EOpBitFieldReverse:
5448 unaryOp = spv::OpBitReverse;
5449 break;
5450 case glslang::EOpBitCount:
5451 unaryOp = spv::OpBitCount;
5452 break;
5453 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005454 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005455 break;
5456 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005457 if (isUnsigned)
5458 libCall = spv::GLSLstd450FindUMsb;
5459 else
5460 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005461 break;
5462
Rex Xu574ab042016-04-14 16:53:07 +08005463 case glslang::EOpBallot:
5464 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005465 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005466 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005467 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005468#ifdef AMD_EXTENSIONS
5469 case glslang::EOpMinInvocations:
5470 case glslang::EOpMaxInvocations:
5471 case glslang::EOpAddInvocations:
5472 case glslang::EOpMinInvocationsNonUniform:
5473 case glslang::EOpMaxInvocationsNonUniform:
5474 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005475 case glslang::EOpMinInvocationsInclusiveScan:
5476 case glslang::EOpMaxInvocationsInclusiveScan:
5477 case glslang::EOpAddInvocationsInclusiveScan:
5478 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5479 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5480 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5481 case glslang::EOpMinInvocationsExclusiveScan:
5482 case glslang::EOpMaxInvocationsExclusiveScan:
5483 case glslang::EOpAddInvocationsExclusiveScan:
5484 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5485 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5486 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005487#endif
Rex Xu51596642016-09-21 18:56:12 +08005488 {
5489 std::vector<spv::Id> operands;
5490 operands.push_back(operand);
5491 return createInvocationsOperation(op, typeId, operands, typeProxy);
5492 }
John Kessenich66011cb2018-03-06 16:12:04 -07005493 case glslang::EOpSubgroupAll:
5494 case glslang::EOpSubgroupAny:
5495 case glslang::EOpSubgroupAllEqual:
5496 case glslang::EOpSubgroupBroadcastFirst:
5497 case glslang::EOpSubgroupBallot:
5498 case glslang::EOpSubgroupInverseBallot:
5499 case glslang::EOpSubgroupBallotBitCount:
5500 case glslang::EOpSubgroupBallotInclusiveBitCount:
5501 case glslang::EOpSubgroupBallotExclusiveBitCount:
5502 case glslang::EOpSubgroupBallotFindLSB:
5503 case glslang::EOpSubgroupBallotFindMSB:
5504 case glslang::EOpSubgroupAdd:
5505 case glslang::EOpSubgroupMul:
5506 case glslang::EOpSubgroupMin:
5507 case glslang::EOpSubgroupMax:
5508 case glslang::EOpSubgroupAnd:
5509 case glslang::EOpSubgroupOr:
5510 case glslang::EOpSubgroupXor:
5511 case glslang::EOpSubgroupInclusiveAdd:
5512 case glslang::EOpSubgroupInclusiveMul:
5513 case glslang::EOpSubgroupInclusiveMin:
5514 case glslang::EOpSubgroupInclusiveMax:
5515 case glslang::EOpSubgroupInclusiveAnd:
5516 case glslang::EOpSubgroupInclusiveOr:
5517 case glslang::EOpSubgroupInclusiveXor:
5518 case glslang::EOpSubgroupExclusiveAdd:
5519 case glslang::EOpSubgroupExclusiveMul:
5520 case glslang::EOpSubgroupExclusiveMin:
5521 case glslang::EOpSubgroupExclusiveMax:
5522 case glslang::EOpSubgroupExclusiveAnd:
5523 case glslang::EOpSubgroupExclusiveOr:
5524 case glslang::EOpSubgroupExclusiveXor:
5525 case glslang::EOpSubgroupQuadSwapHorizontal:
5526 case glslang::EOpSubgroupQuadSwapVertical:
5527 case glslang::EOpSubgroupQuadSwapDiagonal: {
5528 std::vector<spv::Id> operands;
5529 operands.push_back(operand);
5530 return createSubgroupOperation(op, typeId, operands, typeProxy);
5531 }
Rex Xu9d93a232016-05-05 12:30:44 +08005532#ifdef AMD_EXTENSIONS
5533 case glslang::EOpMbcnt:
5534 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5535 libCall = spv::MbcntAMD;
5536 break;
5537
5538 case glslang::EOpCubeFaceIndex:
5539 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5540 libCall = spv::CubeFaceIndexAMD;
5541 break;
5542
5543 case glslang::EOpCubeFaceCoord:
5544 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5545 libCall = spv::CubeFaceCoordAMD;
5546 break;
5547#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005548#ifdef NV_EXTENSIONS
5549 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005550 unaryOp = spv::OpGroupNonUniformPartitionNV;
5551 break;
5552#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005553 case glslang::EOpConstructReference:
5554 unaryOp = spv::OpBitcast;
5555 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005556 default:
5557 return 0;
5558 }
5559
5560 spv::Id id;
5561 if (libCall >= 0) {
5562 std::vector<spv::Id> args;
5563 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005564 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005565 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005566 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005567 }
John Kessenich140f3df2015-06-26 16:58:36 -06005568
John Kessenichead86222018-03-28 18:01:20 -06005569 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005570 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005571 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005572}
5573
John Kessenich7a53f762016-01-20 11:19:27 -07005574// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005575spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5576 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005577{
5578 // Handle unary operations vector by vector.
5579 // The result type is the same type as the original type.
5580 // The algorithm is to:
5581 // - break the matrix into vectors
5582 // - apply the operation to each vector
5583 // - make a matrix out the vector results
5584
5585 // get the types sorted out
5586 int numCols = builder.getNumColumns(operand);
5587 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005588 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5589 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005590 std::vector<spv::Id> results;
5591
5592 // do each vector op
5593 for (int c = 0; c < numCols; ++c) {
5594 std::vector<unsigned int> indexes;
5595 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005596 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5597 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005598 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005599 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005600 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005601 }
5602
5603 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005604 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005605 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005606 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005607}
5608
John Kessenichad7645f2018-06-04 19:11:25 -06005609// For converting integers where both the bitwidth and the signedness could
5610// change, but only do the width change here. The caller is still responsible
5611// for the signedness conversion.
5612spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005613{
John Kessenichad7645f2018-06-04 19:11:25 -06005614 // Get the result type width, based on the type to convert to.
5615 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005616 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005617 case glslang::EOpConvInt16ToUint8:
5618 case glslang::EOpConvIntToUint8:
5619 case glslang::EOpConvInt64ToUint8:
5620 case glslang::EOpConvUint16ToInt8:
5621 case glslang::EOpConvUintToInt8:
5622 case glslang::EOpConvUint64ToInt8:
5623 width = 8;
5624 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005625 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005626 case glslang::EOpConvIntToUint16:
5627 case glslang::EOpConvInt64ToUint16:
5628 case glslang::EOpConvUint8ToInt16:
5629 case glslang::EOpConvUintToInt16:
5630 case glslang::EOpConvUint64ToInt16:
5631 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005632 break;
5633 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005634 case glslang::EOpConvInt16ToUint:
5635 case glslang::EOpConvInt64ToUint:
5636 case glslang::EOpConvUint8ToInt:
5637 case glslang::EOpConvUint16ToInt:
5638 case glslang::EOpConvUint64ToInt:
5639 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005640 break;
5641 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005642 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005643 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005644 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005645 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005646 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005647 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005648 break;
5649
5650 default:
5651 assert(false && "Default missing");
5652 break;
5653 }
5654
John Kessenichad7645f2018-06-04 19:11:25 -06005655 // Get the conversion operation and result type,
5656 // based on the target width, but the source type.
5657 spv::Id type = spv::NoType;
5658 spv::Op convOp = spv::OpNop;
5659 switch(op) {
5660 case glslang::EOpConvInt8ToUint16:
5661 case glslang::EOpConvInt8ToUint:
5662 case glslang::EOpConvInt8ToUint64:
5663 case glslang::EOpConvInt16ToUint8:
5664 case glslang::EOpConvInt16ToUint:
5665 case glslang::EOpConvInt16ToUint64:
5666 case glslang::EOpConvIntToUint8:
5667 case glslang::EOpConvIntToUint16:
5668 case glslang::EOpConvIntToUint64:
5669 case glslang::EOpConvInt64ToUint8:
5670 case glslang::EOpConvInt64ToUint16:
5671 case glslang::EOpConvInt64ToUint:
5672 convOp = spv::OpSConvert;
5673 type = builder.makeIntType(width);
5674 break;
5675 default:
5676 convOp = spv::OpUConvert;
5677 type = builder.makeUintType(width);
5678 break;
5679 }
5680
John Kessenich66011cb2018-03-06 16:12:04 -07005681 if (vectorSize > 0)
5682 type = builder.makeVectorType(type, vectorSize);
5683
John Kessenichad7645f2018-06-04 19:11:25 -06005684 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005685}
5686
John Kessenichead86222018-03-28 18:01:20 -06005687spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5688 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005689{
5690 spv::Op convOp = spv::OpNop;
5691 spv::Id zero = 0;
5692 spv::Id one = 0;
5693
5694 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5695
5696 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005697 case glslang::EOpConvInt8ToBool:
5698 case glslang::EOpConvUint8ToBool:
5699 zero = builder.makeUint8Constant(0);
5700 zero = makeSmearedConstant(zero, vectorSize);
5701 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005702 case glslang::EOpConvInt16ToBool:
5703 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005704 zero = builder.makeUint16Constant(0);
5705 zero = makeSmearedConstant(zero, vectorSize);
5706 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5707 case glslang::EOpConvIntToBool:
5708 case glslang::EOpConvUintToBool:
5709 zero = builder.makeUintConstant(0);
5710 zero = makeSmearedConstant(zero, vectorSize);
5711 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5712 case glslang::EOpConvInt64ToBool:
5713 case glslang::EOpConvUint64ToBool:
5714 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005715 zero = makeSmearedConstant(zero, vectorSize);
5716 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5717
5718 case glslang::EOpConvFloatToBool:
5719 zero = builder.makeFloatConstant(0.0F);
5720 zero = makeSmearedConstant(zero, vectorSize);
5721 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5722
5723 case glslang::EOpConvDoubleToBool:
5724 zero = builder.makeDoubleConstant(0.0);
5725 zero = makeSmearedConstant(zero, vectorSize);
5726 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5727
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005728 case glslang::EOpConvFloat16ToBool:
5729 zero = builder.makeFloat16Constant(0.0F);
5730 zero = makeSmearedConstant(zero, vectorSize);
5731 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005732
John Kessenich140f3df2015-06-26 16:58:36 -06005733 case glslang::EOpConvBoolToFloat:
5734 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005735 zero = builder.makeFloatConstant(0.0F);
5736 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005737 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005738
John Kessenich140f3df2015-06-26 16:58:36 -06005739 case glslang::EOpConvBoolToDouble:
5740 convOp = spv::OpSelect;
5741 zero = builder.makeDoubleConstant(0.0);
5742 one = builder.makeDoubleConstant(1.0);
5743 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005744
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005745 case glslang::EOpConvBoolToFloat16:
5746 convOp = spv::OpSelect;
5747 zero = builder.makeFloat16Constant(0.0F);
5748 one = builder.makeFloat16Constant(1.0F);
5749 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005750
5751 case glslang::EOpConvBoolToInt8:
5752 zero = builder.makeInt8Constant(0);
5753 one = builder.makeInt8Constant(1);
5754 convOp = spv::OpSelect;
5755 break;
5756
5757 case glslang::EOpConvBoolToUint8:
5758 zero = builder.makeUint8Constant(0);
5759 one = builder.makeUint8Constant(1);
5760 convOp = spv::OpSelect;
5761 break;
5762
5763 case glslang::EOpConvBoolToInt16:
5764 zero = builder.makeInt16Constant(0);
5765 one = builder.makeInt16Constant(1);
5766 convOp = spv::OpSelect;
5767 break;
5768
5769 case glslang::EOpConvBoolToUint16:
5770 zero = builder.makeUint16Constant(0);
5771 one = builder.makeUint16Constant(1);
5772 convOp = spv::OpSelect;
5773 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005774
John Kessenich140f3df2015-06-26 16:58:36 -06005775 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005776 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005777 if (op == glslang::EOpConvBoolToInt64)
5778 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005779 else
5780 zero = builder.makeIntConstant(0);
5781
5782 if (op == glslang::EOpConvBoolToInt64)
5783 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005784 else
5785 one = builder.makeIntConstant(1);
5786
John Kessenich140f3df2015-06-26 16:58:36 -06005787 convOp = spv::OpSelect;
5788 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005789
John Kessenich140f3df2015-06-26 16:58:36 -06005790 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005791 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005792 if (op == glslang::EOpConvBoolToUint64)
5793 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005794 else
5795 zero = builder.makeUintConstant(0);
5796
5797 if (op == glslang::EOpConvBoolToUint64)
5798 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005799 else
5800 one = builder.makeUintConstant(1);
5801
John Kessenich140f3df2015-06-26 16:58:36 -06005802 convOp = spv::OpSelect;
5803 break;
5804
John Kessenich66011cb2018-03-06 16:12:04 -07005805 case glslang::EOpConvInt8ToFloat16:
5806 case glslang::EOpConvInt8ToFloat:
5807 case glslang::EOpConvInt8ToDouble:
5808 case glslang::EOpConvInt16ToFloat16:
5809 case glslang::EOpConvInt16ToFloat:
5810 case glslang::EOpConvInt16ToDouble:
5811 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005812 case glslang::EOpConvIntToFloat:
5813 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005814 case glslang::EOpConvInt64ToFloat:
5815 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005816 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005817 convOp = spv::OpConvertSToF;
5818 break;
5819
John Kessenich66011cb2018-03-06 16:12:04 -07005820 case glslang::EOpConvUint8ToFloat16:
5821 case glslang::EOpConvUint8ToFloat:
5822 case glslang::EOpConvUint8ToDouble:
5823 case glslang::EOpConvUint16ToFloat16:
5824 case glslang::EOpConvUint16ToFloat:
5825 case glslang::EOpConvUint16ToDouble:
5826 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005827 case glslang::EOpConvUintToFloat:
5828 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005829 case glslang::EOpConvUint64ToFloat:
5830 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005831 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005832 convOp = spv::OpConvertUToF;
5833 break;
5834
5835 case glslang::EOpConvDoubleToFloat:
5836 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005837 case glslang::EOpConvDoubleToFloat16:
5838 case glslang::EOpConvFloat16ToDouble:
5839 case glslang::EOpConvFloatToFloat16:
5840 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005841 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005842 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005843 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005844 break;
5845
John Kessenich66011cb2018-03-06 16:12:04 -07005846 case glslang::EOpConvFloat16ToInt8:
5847 case glslang::EOpConvFloatToInt8:
5848 case glslang::EOpConvDoubleToInt8:
5849 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005850 case glslang::EOpConvFloatToInt16:
5851 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005852 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005853 case glslang::EOpConvFloatToInt:
5854 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005855 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005856 case glslang::EOpConvFloatToInt64:
5857 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005858 convOp = spv::OpConvertFToS;
5859 break;
5860
John Kessenich66011cb2018-03-06 16:12:04 -07005861 case glslang::EOpConvUint8ToInt8:
5862 case glslang::EOpConvInt8ToUint8:
5863 case glslang::EOpConvUint16ToInt16:
5864 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005865 case glslang::EOpConvUintToInt:
5866 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005867 case glslang::EOpConvUint64ToInt64:
5868 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005869 if (builder.isInSpecConstCodeGenMode()) {
5870 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005871 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5872 zero = builder.makeUint8Constant(0);
5873 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005874 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005875 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5876 zero = builder.makeUint64Constant(0);
5877 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005878 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005879 }
qining189b2032016-04-12 23:16:20 -04005880 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005881 // Use OpIAdd, instead of OpBitcast to do the conversion when
5882 // generating for OpSpecConstantOp instruction.
5883 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5884 }
5885 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005886 convOp = spv::OpBitcast;
5887 break;
5888
John Kessenich66011cb2018-03-06 16:12:04 -07005889 case glslang::EOpConvFloat16ToUint8:
5890 case glslang::EOpConvFloatToUint8:
5891 case glslang::EOpConvDoubleToUint8:
5892 case glslang::EOpConvFloat16ToUint16:
5893 case glslang::EOpConvFloatToUint16:
5894 case glslang::EOpConvDoubleToUint16:
5895 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005896 case glslang::EOpConvFloatToUint:
5897 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005898 case glslang::EOpConvFloatToUint64:
5899 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005900 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005901 convOp = spv::OpConvertFToU;
5902 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005903
John Kessenich66011cb2018-03-06 16:12:04 -07005904 case glslang::EOpConvInt8ToInt16:
5905 case glslang::EOpConvInt8ToInt:
5906 case glslang::EOpConvInt8ToInt64:
5907 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005908 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005909 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005910 case glslang::EOpConvIntToInt8:
5911 case glslang::EOpConvIntToInt16:
5912 case glslang::EOpConvIntToInt64:
5913 case glslang::EOpConvInt64ToInt8:
5914 case glslang::EOpConvInt64ToInt16:
5915 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005916 convOp = spv::OpSConvert;
5917 break;
5918
John Kessenich66011cb2018-03-06 16:12:04 -07005919 case glslang::EOpConvUint8ToUint16:
5920 case glslang::EOpConvUint8ToUint:
5921 case glslang::EOpConvUint8ToUint64:
5922 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005923 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005924 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005925 case glslang::EOpConvUintToUint8:
5926 case glslang::EOpConvUintToUint16:
5927 case glslang::EOpConvUintToUint64:
5928 case glslang::EOpConvUint64ToUint8:
5929 case glslang::EOpConvUint64ToUint16:
5930 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005931 convOp = spv::OpUConvert;
5932 break;
5933
John Kessenich66011cb2018-03-06 16:12:04 -07005934 case glslang::EOpConvInt8ToUint16:
5935 case glslang::EOpConvInt8ToUint:
5936 case glslang::EOpConvInt8ToUint64:
5937 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005938 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005939 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005940 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005941 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005942 case glslang::EOpConvIntToUint64:
5943 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005944 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005945 case glslang::EOpConvInt64ToUint:
5946 case glslang::EOpConvUint8ToInt16:
5947 case glslang::EOpConvUint8ToInt:
5948 case glslang::EOpConvUint8ToInt64:
5949 case glslang::EOpConvUint16ToInt8:
5950 case glslang::EOpConvUint16ToInt:
5951 case glslang::EOpConvUint16ToInt64:
5952 case glslang::EOpConvUintToInt8:
5953 case glslang::EOpConvUintToInt16:
5954 case glslang::EOpConvUintToInt64:
5955 case glslang::EOpConvUint64ToInt8:
5956 case glslang::EOpConvUint64ToInt16:
5957 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005958 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005959 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005960
5961 if (builder.isInSpecConstCodeGenMode()) {
5962 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005963 switch(op) {
5964 case glslang::EOpConvInt16ToUint8:
5965 case glslang::EOpConvIntToUint8:
5966 case glslang::EOpConvInt64ToUint8:
5967 case glslang::EOpConvUint16ToInt8:
5968 case glslang::EOpConvUintToInt8:
5969 case glslang::EOpConvUint64ToInt8:
5970 zero = builder.makeUint8Constant(0);
5971 break;
5972 case glslang::EOpConvInt8ToUint16:
5973 case glslang::EOpConvIntToUint16:
5974 case glslang::EOpConvInt64ToUint16:
5975 case glslang::EOpConvUint8ToInt16:
5976 case glslang::EOpConvUintToInt16:
5977 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005978 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005979 break;
5980 case glslang::EOpConvInt8ToUint:
5981 case glslang::EOpConvInt16ToUint:
5982 case glslang::EOpConvInt64ToUint:
5983 case glslang::EOpConvUint8ToInt:
5984 case glslang::EOpConvUint16ToInt:
5985 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005986 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005987 break;
5988 case glslang::EOpConvInt8ToUint64:
5989 case glslang::EOpConvInt16ToUint64:
5990 case glslang::EOpConvIntToUint64:
5991 case glslang::EOpConvUint8ToInt64:
5992 case glslang::EOpConvUint16ToInt64:
5993 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005994 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005995 break;
5996 default:
5997 assert(false && "Default missing");
5998 break;
5999 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006000 zero = makeSmearedConstant(zero, vectorSize);
6001 // Use OpIAdd, instead of OpBitcast to do the conversion when
6002 // generating for OpSpecConstantOp instruction.
6003 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6004 }
6005 // For normal run-time conversion instruction, use OpBitcast.
6006 convOp = spv::OpBitcast;
6007 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006008 case glslang::EOpConvUint64ToPtr:
6009 convOp = spv::OpConvertUToPtr;
6010 break;
6011 case glslang::EOpConvPtrToUint64:
6012 convOp = spv::OpConvertPtrToU;
6013 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006014 default:
6015 break;
6016 }
6017
6018 spv::Id result = 0;
6019 if (convOp == spv::OpNop)
6020 return result;
6021
6022 if (convOp == spv::OpSelect) {
6023 zero = makeSmearedConstant(zero, vectorSize);
6024 one = makeSmearedConstant(one, vectorSize);
6025 result = builder.createTriOp(convOp, destType, operand, one, zero);
6026 } else
6027 result = builder.createUnaryOp(convOp, destType, operand);
6028
John Kessenichead86222018-03-28 18:01:20 -06006029 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006030 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006031 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006032}
6033
6034spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6035{
6036 if (vectorSize == 0)
6037 return constant;
6038
6039 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6040 std::vector<spv::Id> components;
6041 for (int c = 0; c < vectorSize; ++c)
6042 components.push_back(constant);
6043 return builder.makeCompositeConstant(vectorTypeId, components);
6044}
6045
John Kessenich426394d2015-07-23 10:22:48 -06006046// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006047spv::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 -06006048{
6049 spv::Op opCode = spv::OpNop;
6050
6051 switch (op) {
6052 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006053 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006054 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006055 opCode = spv::OpAtomicIAdd;
6056 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006057 case glslang::EOpAtomicCounterSubtract:
6058 opCode = spv::OpAtomicISub;
6059 break;
John Kessenich426394d2015-07-23 10:22:48 -06006060 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006061 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006062 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006063 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006064 break;
6065 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006066 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006067 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006068 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006069 break;
6070 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006071 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006072 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006073 opCode = spv::OpAtomicAnd;
6074 break;
6075 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006076 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006077 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006078 opCode = spv::OpAtomicOr;
6079 break;
6080 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006081 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006082 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006083 opCode = spv::OpAtomicXor;
6084 break;
6085 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006086 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006087 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006088 opCode = spv::OpAtomicExchange;
6089 break;
6090 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006091 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006092 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006093 opCode = spv::OpAtomicCompareExchange;
6094 break;
6095 case glslang::EOpAtomicCounterIncrement:
6096 opCode = spv::OpAtomicIIncrement;
6097 break;
6098 case glslang::EOpAtomicCounterDecrement:
6099 opCode = spv::OpAtomicIDecrement;
6100 break;
6101 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006102 case glslang::EOpImageAtomicLoad:
6103 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006104 opCode = spv::OpAtomicLoad;
6105 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006106 case glslang::EOpAtomicStore:
6107 case glslang::EOpImageAtomicStore:
6108 opCode = spv::OpAtomicStore;
6109 break;
John Kessenich426394d2015-07-23 10:22:48 -06006110 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006111 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006112 break;
6113 }
6114
Rex Xue8fe8b02017-09-26 15:42:56 +08006115 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6116 builder.addCapability(spv::CapabilityInt64Atomics);
6117
John Kessenich426394d2015-07-23 10:22:48 -06006118 // Sort out the operands
6119 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006120 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006121 // - compare-exchange swaps the value and comparator
6122 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006123 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006124 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6125 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6126 spv::Id scopeId;
6127 if (glslangIntermediate->usingVulkanMemoryModel()) {
6128 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6129 } else {
6130 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6131 }
6132 // semantics default to relaxed
6133 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6134 spv::Id semanticsId2 = semanticsId;
6135
6136 pointerId = operands[0];
6137 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6138 // no additional operands
6139 } else if (opCode == spv::OpAtomicCompareExchange) {
6140 compareId = operands[1];
6141 valueId = operands[2];
6142 if (operands.size() > 3) {
6143 scopeId = operands[3];
6144 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6145 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6146 }
6147 } else if (opCode == spv::OpAtomicLoad) {
6148 if (operands.size() > 1) {
6149 scopeId = operands[1];
6150 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6151 }
6152 } else {
6153 // atomic store or RMW
6154 valueId = operands[1];
6155 if (operands.size() > 2) {
6156 scopeId = operands[2];
6157 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6158 }
Rex Xu04db3f52015-09-16 11:44:02 +08006159 }
John Kessenich426394d2015-07-23 10:22:48 -06006160
Jeff Bolz36831c92018-09-05 10:11:41 -05006161 // Check for capabilities
6162 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6163 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6164 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6165 }
John Kessenich426394d2015-07-23 10:22:48 -06006166
Jeff Bolz36831c92018-09-05 10:11:41 -05006167 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6168 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6169 }
John Kessenich48d6e792017-10-06 21:21:48 -06006170
Jeff Bolz36831c92018-09-05 10:11:41 -05006171 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6172 spvAtomicOperands.push_back(pointerId);
6173 spvAtomicOperands.push_back(scopeId);
6174 spvAtomicOperands.push_back(semanticsId);
6175 if (opCode == spv::OpAtomicCompareExchange) {
6176 spvAtomicOperands.push_back(semanticsId2);
6177 spvAtomicOperands.push_back(valueId);
6178 spvAtomicOperands.push_back(compareId);
6179 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6180 spvAtomicOperands.push_back(valueId);
6181 }
John Kessenich48d6e792017-10-06 21:21:48 -06006182
Jeff Bolz36831c92018-09-05 10:11:41 -05006183 if (opCode == spv::OpAtomicStore) {
6184 builder.createNoResultOp(opCode, spvAtomicOperands);
6185 return 0;
6186 } else {
6187 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6188
6189 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6190 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6191 if (op == glslang::EOpAtomicCounterDecrement)
6192 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6193
6194 return resultId;
6195 }
John Kessenich426394d2015-07-23 10:22:48 -06006196}
6197
John Kessenich91cef522016-05-05 16:45:40 -06006198// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006199spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006200{
Corentin Walleze7061422018-08-08 15:20:15 +02006201#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006202 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6203 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006204#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006205
Rex Xu51596642016-09-21 18:56:12 +08006206 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006207 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006208 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6209
chaocf200da82016-12-20 12:44:35 -08006210 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6211 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006212 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6213 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006214 } else if (op == glslang::EOpAnyInvocation ||
6215 op == glslang::EOpAllInvocations ||
6216 op == glslang::EOpAllInvocationsEqual) {
6217 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6218 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006219 } else {
6220 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006221#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006222 if (op == glslang::EOpMinInvocationsNonUniform ||
6223 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006224 op == glslang::EOpAddInvocationsNonUniform ||
6225 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6226 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6227 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6228 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6229 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6230 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006231 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006232#endif
Rex Xu51596642016-09-21 18:56:12 +08006233
Rex Xu9d93a232016-05-05 12:30:44 +08006234#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006235 switch (op) {
6236 case glslang::EOpMinInvocations:
6237 case glslang::EOpMaxInvocations:
6238 case glslang::EOpAddInvocations:
6239 case glslang::EOpMinInvocationsNonUniform:
6240 case glslang::EOpMaxInvocationsNonUniform:
6241 case glslang::EOpAddInvocationsNonUniform:
6242 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006243 break;
6244 case glslang::EOpMinInvocationsInclusiveScan:
6245 case glslang::EOpMaxInvocationsInclusiveScan:
6246 case glslang::EOpAddInvocationsInclusiveScan:
6247 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6248 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6249 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6250 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006251 break;
6252 case glslang::EOpMinInvocationsExclusiveScan:
6253 case glslang::EOpMaxInvocationsExclusiveScan:
6254 case glslang::EOpAddInvocationsExclusiveScan:
6255 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6256 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6257 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6258 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006259 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006260 default:
6261 break;
Rex Xu430ef402016-10-14 17:22:23 +08006262 }
John Kessenich149afc32018-08-14 13:31:43 -06006263 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6264 spvGroupOperands.push_back(scope);
6265 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006266 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006267 spvGroupOperands.push_back(groupOp);
6268 }
Rex Xu9d93a232016-05-05 12:30:44 +08006269#endif
Rex Xu51596642016-09-21 18:56:12 +08006270 }
6271
John Kessenich149afc32018-08-14 13:31:43 -06006272 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6273 spv::IdImmediate op = { true, *opIt };
6274 spvGroupOperands.push_back(op);
6275 }
John Kessenich91cef522016-05-05 16:45:40 -06006276
6277 switch (op) {
6278 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006279 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006280 break;
John Kessenich91cef522016-05-05 16:45:40 -06006281 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006282 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006283 break;
John Kessenich91cef522016-05-05 16:45:40 -06006284 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006285 opCode = spv::OpSubgroupAllEqualKHR;
6286 break;
Rex Xu51596642016-09-21 18:56:12 +08006287 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006288 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006289 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006290 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006291 break;
6292 case glslang::EOpReadFirstInvocation:
6293 opCode = spv::OpSubgroupFirstInvocationKHR;
6294 break;
6295 case glslang::EOpBallot:
6296 {
6297 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6298 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6299 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6300 //
6301 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6302 //
6303 spv::Id uintType = builder.makeUintType(32);
6304 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6305 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6306
6307 std::vector<spv::Id> components;
6308 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6309 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6310
6311 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6312 return builder.createUnaryOp(spv::OpBitcast, typeId,
6313 builder.createCompositeConstruct(uvec2Type, components));
6314 }
6315
Rex Xu9d93a232016-05-05 12:30:44 +08006316#ifdef AMD_EXTENSIONS
6317 case glslang::EOpMinInvocations:
6318 case glslang::EOpMaxInvocations:
6319 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006320 case glslang::EOpMinInvocationsInclusiveScan:
6321 case glslang::EOpMaxInvocationsInclusiveScan:
6322 case glslang::EOpAddInvocationsInclusiveScan:
6323 case glslang::EOpMinInvocationsExclusiveScan:
6324 case glslang::EOpMaxInvocationsExclusiveScan:
6325 case glslang::EOpAddInvocationsExclusiveScan:
6326 if (op == glslang::EOpMinInvocations ||
6327 op == glslang::EOpMinInvocationsInclusiveScan ||
6328 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006329 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006330 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006331 else {
6332 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006333 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006334 else
Rex Xu51596642016-09-21 18:56:12 +08006335 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006336 }
Rex Xu430ef402016-10-14 17:22:23 +08006337 } else if (op == glslang::EOpMaxInvocations ||
6338 op == glslang::EOpMaxInvocationsInclusiveScan ||
6339 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006340 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006341 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006342 else {
6343 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006344 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006345 else
Rex Xu51596642016-09-21 18:56:12 +08006346 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006347 }
6348 } else {
6349 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006350 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006351 else
Rex Xu51596642016-09-21 18:56:12 +08006352 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006353 }
6354
Rex Xu2bbbe062016-08-23 15:41:05 +08006355 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006356 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006357
6358 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006359 case glslang::EOpMinInvocationsNonUniform:
6360 case glslang::EOpMaxInvocationsNonUniform:
6361 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006362 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6363 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6364 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6365 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6366 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6367 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6368 if (op == glslang::EOpMinInvocationsNonUniform ||
6369 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6370 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006371 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006372 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006373 else {
6374 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006375 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006376 else
Rex Xu51596642016-09-21 18:56:12 +08006377 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006378 }
6379 }
Rex Xu430ef402016-10-14 17:22:23 +08006380 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6381 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6382 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006383 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006384 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006385 else {
6386 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006387 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006388 else
Rex Xu51596642016-09-21 18:56:12 +08006389 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006390 }
6391 }
6392 else {
6393 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006394 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006395 else
Rex Xu51596642016-09-21 18:56:12 +08006396 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006397 }
6398
Rex Xu2bbbe062016-08-23 15:41:05 +08006399 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006400 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006401
6402 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006403#endif
John Kessenich91cef522016-05-05 16:45:40 -06006404 default:
6405 logger->missingFunctionality("invocation operation");
6406 return spv::NoResult;
6407 }
Rex Xu51596642016-09-21 18:56:12 +08006408
6409 assert(opCode != spv::OpNop);
6410 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006411}
6412
Rex Xu2bbbe062016-08-23 15:41:05 +08006413// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006414spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6415 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006416{
Rex Xub7072052016-09-26 15:53:40 +08006417#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006418 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6419 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006420 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006421 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006422 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6423 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6424 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006425#else
6426 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6427 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006428 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6429 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006430#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006431
6432 // Handle group invocation operations scalar by scalar.
6433 // The result type is the same type as the original type.
6434 // The algorithm is to:
6435 // - break the vector into scalars
6436 // - apply the operation to each scalar
6437 // - make a vector out the scalar results
6438
6439 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006440 int numComponents = builder.getNumComponents(operands[0]);
6441 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006442 std::vector<spv::Id> results;
6443
6444 // do each scalar op
6445 for (int comp = 0; comp < numComponents; ++comp) {
6446 std::vector<unsigned int> indexes;
6447 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006448 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6449 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006450 if (op == spv::OpSubgroupReadInvocationKHR) {
6451 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006452 spv::IdImmediate operand = { true, operands[1] };
6453 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006454 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006455 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6456 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006457 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006458 spv::IdImmediate operand = { true, operands[1] };
6459 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006460 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006461 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6462 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006463 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006464 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006465 spvGroupOperands.push_back(scalar);
6466 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006467
Rex Xub7072052016-09-26 15:53:40 +08006468 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006469 }
6470
6471 // put the pieces together
6472 return builder.createCompositeConstruct(typeId, results);
6473}
Rex Xu2bbbe062016-08-23 15:41:05 +08006474
John Kessenich66011cb2018-03-06 16:12:04 -07006475// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006476spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6477 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006478{
6479 // Add the required capabilities.
6480 switch (op) {
6481 case glslang::EOpSubgroupElect:
6482 builder.addCapability(spv::CapabilityGroupNonUniform);
6483 break;
6484 case glslang::EOpSubgroupAll:
6485 case glslang::EOpSubgroupAny:
6486 case glslang::EOpSubgroupAllEqual:
6487 builder.addCapability(spv::CapabilityGroupNonUniform);
6488 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6489 break;
6490 case glslang::EOpSubgroupBroadcast:
6491 case glslang::EOpSubgroupBroadcastFirst:
6492 case glslang::EOpSubgroupBallot:
6493 case glslang::EOpSubgroupInverseBallot:
6494 case glslang::EOpSubgroupBallotBitExtract:
6495 case glslang::EOpSubgroupBallotBitCount:
6496 case glslang::EOpSubgroupBallotInclusiveBitCount:
6497 case glslang::EOpSubgroupBallotExclusiveBitCount:
6498 case glslang::EOpSubgroupBallotFindLSB:
6499 case glslang::EOpSubgroupBallotFindMSB:
6500 builder.addCapability(spv::CapabilityGroupNonUniform);
6501 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6502 break;
6503 case glslang::EOpSubgroupShuffle:
6504 case glslang::EOpSubgroupShuffleXor:
6505 builder.addCapability(spv::CapabilityGroupNonUniform);
6506 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6507 break;
6508 case glslang::EOpSubgroupShuffleUp:
6509 case glslang::EOpSubgroupShuffleDown:
6510 builder.addCapability(spv::CapabilityGroupNonUniform);
6511 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6512 break;
6513 case glslang::EOpSubgroupAdd:
6514 case glslang::EOpSubgroupMul:
6515 case glslang::EOpSubgroupMin:
6516 case glslang::EOpSubgroupMax:
6517 case glslang::EOpSubgroupAnd:
6518 case glslang::EOpSubgroupOr:
6519 case glslang::EOpSubgroupXor:
6520 case glslang::EOpSubgroupInclusiveAdd:
6521 case glslang::EOpSubgroupInclusiveMul:
6522 case glslang::EOpSubgroupInclusiveMin:
6523 case glslang::EOpSubgroupInclusiveMax:
6524 case glslang::EOpSubgroupInclusiveAnd:
6525 case glslang::EOpSubgroupInclusiveOr:
6526 case glslang::EOpSubgroupInclusiveXor:
6527 case glslang::EOpSubgroupExclusiveAdd:
6528 case glslang::EOpSubgroupExclusiveMul:
6529 case glslang::EOpSubgroupExclusiveMin:
6530 case glslang::EOpSubgroupExclusiveMax:
6531 case glslang::EOpSubgroupExclusiveAnd:
6532 case glslang::EOpSubgroupExclusiveOr:
6533 case glslang::EOpSubgroupExclusiveXor:
6534 builder.addCapability(spv::CapabilityGroupNonUniform);
6535 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6536 break;
6537 case glslang::EOpSubgroupClusteredAdd:
6538 case glslang::EOpSubgroupClusteredMul:
6539 case glslang::EOpSubgroupClusteredMin:
6540 case glslang::EOpSubgroupClusteredMax:
6541 case glslang::EOpSubgroupClusteredAnd:
6542 case glslang::EOpSubgroupClusteredOr:
6543 case glslang::EOpSubgroupClusteredXor:
6544 builder.addCapability(spv::CapabilityGroupNonUniform);
6545 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6546 break;
6547 case glslang::EOpSubgroupQuadBroadcast:
6548 case glslang::EOpSubgroupQuadSwapHorizontal:
6549 case glslang::EOpSubgroupQuadSwapVertical:
6550 case glslang::EOpSubgroupQuadSwapDiagonal:
6551 builder.addCapability(spv::CapabilityGroupNonUniform);
6552 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6553 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006554#ifdef NV_EXTENSIONS
6555 case glslang::EOpSubgroupPartitionedAdd:
6556 case glslang::EOpSubgroupPartitionedMul:
6557 case glslang::EOpSubgroupPartitionedMin:
6558 case glslang::EOpSubgroupPartitionedMax:
6559 case glslang::EOpSubgroupPartitionedAnd:
6560 case glslang::EOpSubgroupPartitionedOr:
6561 case glslang::EOpSubgroupPartitionedXor:
6562 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6563 case glslang::EOpSubgroupPartitionedInclusiveMul:
6564 case glslang::EOpSubgroupPartitionedInclusiveMin:
6565 case glslang::EOpSubgroupPartitionedInclusiveMax:
6566 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6567 case glslang::EOpSubgroupPartitionedInclusiveOr:
6568 case glslang::EOpSubgroupPartitionedInclusiveXor:
6569 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6570 case glslang::EOpSubgroupPartitionedExclusiveMul:
6571 case glslang::EOpSubgroupPartitionedExclusiveMin:
6572 case glslang::EOpSubgroupPartitionedExclusiveMax:
6573 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6574 case glslang::EOpSubgroupPartitionedExclusiveOr:
6575 case glslang::EOpSubgroupPartitionedExclusiveXor:
6576 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6577 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6578 break;
6579#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006580 default: assert(0 && "Unhandled subgroup operation!");
6581 }
6582
6583 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6584 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6585 const bool isBool = typeProxy == glslang::EbtBool;
6586
6587 spv::Op opCode = spv::OpNop;
6588
6589 // Figure out which opcode to use.
6590 switch (op) {
6591 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6592 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6593 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6594 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6595 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6596 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6597 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6598 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6599 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6600 case glslang::EOpSubgroupBallotBitCount:
6601 case glslang::EOpSubgroupBallotInclusiveBitCount:
6602 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6603 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6604 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6605 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6606 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6607 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6608 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6609 case glslang::EOpSubgroupAdd:
6610 case glslang::EOpSubgroupInclusiveAdd:
6611 case glslang::EOpSubgroupExclusiveAdd:
6612 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006613#ifdef NV_EXTENSIONS
6614 case glslang::EOpSubgroupPartitionedAdd:
6615 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6616 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6617#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006618 if (isFloat) {
6619 opCode = spv::OpGroupNonUniformFAdd;
6620 } else {
6621 opCode = spv::OpGroupNonUniformIAdd;
6622 }
6623 break;
6624 case glslang::EOpSubgroupMul:
6625 case glslang::EOpSubgroupInclusiveMul:
6626 case glslang::EOpSubgroupExclusiveMul:
6627 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006628#ifdef NV_EXTENSIONS
6629 case glslang::EOpSubgroupPartitionedMul:
6630 case glslang::EOpSubgroupPartitionedInclusiveMul:
6631 case glslang::EOpSubgroupPartitionedExclusiveMul:
6632#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006633 if (isFloat) {
6634 opCode = spv::OpGroupNonUniformFMul;
6635 } else {
6636 opCode = spv::OpGroupNonUniformIMul;
6637 }
6638 break;
6639 case glslang::EOpSubgroupMin:
6640 case glslang::EOpSubgroupInclusiveMin:
6641 case glslang::EOpSubgroupExclusiveMin:
6642 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006643#ifdef NV_EXTENSIONS
6644 case glslang::EOpSubgroupPartitionedMin:
6645 case glslang::EOpSubgroupPartitionedInclusiveMin:
6646 case glslang::EOpSubgroupPartitionedExclusiveMin:
6647#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006648 if (isFloat) {
6649 opCode = spv::OpGroupNonUniformFMin;
6650 } else if (isUnsigned) {
6651 opCode = spv::OpGroupNonUniformUMin;
6652 } else {
6653 opCode = spv::OpGroupNonUniformSMin;
6654 }
6655 break;
6656 case glslang::EOpSubgroupMax:
6657 case glslang::EOpSubgroupInclusiveMax:
6658 case glslang::EOpSubgroupExclusiveMax:
6659 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006660#ifdef NV_EXTENSIONS
6661 case glslang::EOpSubgroupPartitionedMax:
6662 case glslang::EOpSubgroupPartitionedInclusiveMax:
6663 case glslang::EOpSubgroupPartitionedExclusiveMax:
6664#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006665 if (isFloat) {
6666 opCode = spv::OpGroupNonUniformFMax;
6667 } else if (isUnsigned) {
6668 opCode = spv::OpGroupNonUniformUMax;
6669 } else {
6670 opCode = spv::OpGroupNonUniformSMax;
6671 }
6672 break;
6673 case glslang::EOpSubgroupAnd:
6674 case glslang::EOpSubgroupInclusiveAnd:
6675 case glslang::EOpSubgroupExclusiveAnd:
6676 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006677#ifdef NV_EXTENSIONS
6678 case glslang::EOpSubgroupPartitionedAnd:
6679 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6680 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6681#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006682 if (isBool) {
6683 opCode = spv::OpGroupNonUniformLogicalAnd;
6684 } else {
6685 opCode = spv::OpGroupNonUniformBitwiseAnd;
6686 }
6687 break;
6688 case glslang::EOpSubgroupOr:
6689 case glslang::EOpSubgroupInclusiveOr:
6690 case glslang::EOpSubgroupExclusiveOr:
6691 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006692#ifdef NV_EXTENSIONS
6693 case glslang::EOpSubgroupPartitionedOr:
6694 case glslang::EOpSubgroupPartitionedInclusiveOr:
6695 case glslang::EOpSubgroupPartitionedExclusiveOr:
6696#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006697 if (isBool) {
6698 opCode = spv::OpGroupNonUniformLogicalOr;
6699 } else {
6700 opCode = spv::OpGroupNonUniformBitwiseOr;
6701 }
6702 break;
6703 case glslang::EOpSubgroupXor:
6704 case glslang::EOpSubgroupInclusiveXor:
6705 case glslang::EOpSubgroupExclusiveXor:
6706 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006707#ifdef NV_EXTENSIONS
6708 case glslang::EOpSubgroupPartitionedXor:
6709 case glslang::EOpSubgroupPartitionedInclusiveXor:
6710 case glslang::EOpSubgroupPartitionedExclusiveXor:
6711#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006712 if (isBool) {
6713 opCode = spv::OpGroupNonUniformLogicalXor;
6714 } else {
6715 opCode = spv::OpGroupNonUniformBitwiseXor;
6716 }
6717 break;
6718 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6719 case glslang::EOpSubgroupQuadSwapHorizontal:
6720 case glslang::EOpSubgroupQuadSwapVertical:
6721 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6722 default: assert(0 && "Unhandled subgroup operation!");
6723 }
6724
John Kessenich149afc32018-08-14 13:31:43 -06006725 // get the right Group Operation
6726 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006727 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006728 default:
6729 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006730 case glslang::EOpSubgroupBallotBitCount:
6731 case glslang::EOpSubgroupAdd:
6732 case glslang::EOpSubgroupMul:
6733 case glslang::EOpSubgroupMin:
6734 case glslang::EOpSubgroupMax:
6735 case glslang::EOpSubgroupAnd:
6736 case glslang::EOpSubgroupOr:
6737 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006738 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006739 break;
6740 case glslang::EOpSubgroupBallotInclusiveBitCount:
6741 case glslang::EOpSubgroupInclusiveAdd:
6742 case glslang::EOpSubgroupInclusiveMul:
6743 case glslang::EOpSubgroupInclusiveMin:
6744 case glslang::EOpSubgroupInclusiveMax:
6745 case glslang::EOpSubgroupInclusiveAnd:
6746 case glslang::EOpSubgroupInclusiveOr:
6747 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006748 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006749 break;
6750 case glslang::EOpSubgroupBallotExclusiveBitCount:
6751 case glslang::EOpSubgroupExclusiveAdd:
6752 case glslang::EOpSubgroupExclusiveMul:
6753 case glslang::EOpSubgroupExclusiveMin:
6754 case glslang::EOpSubgroupExclusiveMax:
6755 case glslang::EOpSubgroupExclusiveAnd:
6756 case glslang::EOpSubgroupExclusiveOr:
6757 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006758 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006759 break;
6760 case glslang::EOpSubgroupClusteredAdd:
6761 case glslang::EOpSubgroupClusteredMul:
6762 case glslang::EOpSubgroupClusteredMin:
6763 case glslang::EOpSubgroupClusteredMax:
6764 case glslang::EOpSubgroupClusteredAnd:
6765 case glslang::EOpSubgroupClusteredOr:
6766 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006767 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006768 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006769#ifdef NV_EXTENSIONS
6770 case glslang::EOpSubgroupPartitionedAdd:
6771 case glslang::EOpSubgroupPartitionedMul:
6772 case glslang::EOpSubgroupPartitionedMin:
6773 case glslang::EOpSubgroupPartitionedMax:
6774 case glslang::EOpSubgroupPartitionedAnd:
6775 case glslang::EOpSubgroupPartitionedOr:
6776 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006777 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006778 break;
6779 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6780 case glslang::EOpSubgroupPartitionedInclusiveMul:
6781 case glslang::EOpSubgroupPartitionedInclusiveMin:
6782 case glslang::EOpSubgroupPartitionedInclusiveMax:
6783 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6784 case glslang::EOpSubgroupPartitionedInclusiveOr:
6785 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006786 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006787 break;
6788 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6789 case glslang::EOpSubgroupPartitionedExclusiveMul:
6790 case glslang::EOpSubgroupPartitionedExclusiveMin:
6791 case glslang::EOpSubgroupPartitionedExclusiveMax:
6792 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6793 case glslang::EOpSubgroupPartitionedExclusiveOr:
6794 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006795 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006796 break;
6797#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006798 }
6799
John Kessenich149afc32018-08-14 13:31:43 -06006800 // build the instruction
6801 std::vector<spv::IdImmediate> spvGroupOperands;
6802
6803 // Every operation begins with the Execution Scope operand.
6804 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6805 spvGroupOperands.push_back(executionScope);
6806
6807 // Next, for all operations that use a Group Operation, push that as an operand.
6808 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006809 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006810 spvGroupOperands.push_back(groupOperand);
6811 }
6812
John Kessenich66011cb2018-03-06 16:12:04 -07006813 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006814 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6815 spv::IdImmediate operand = { true, *opIt };
6816 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006817 }
6818
6819 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006820 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006821 switch (op) {
6822 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006823 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6824 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6825 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6826 }
6827 if (directionId != spv::NoResult) {
6828 spv::IdImmediate direction = { true, directionId };
6829 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006830 }
6831
6832 return builder.createOp(opCode, typeId, spvGroupOperands);
6833}
6834
John Kessenich5e4b1242015-08-06 22:53:06 -06006835spv::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 -06006836{
John Kessenich66011cb2018-03-06 16:12:04 -07006837 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6838 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006839
John Kessenich140f3df2015-06-26 16:58:36 -06006840 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006841 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006842 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006843 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006844 spv::Id typeId0 = 0;
6845 if (consumedOperands > 0)
6846 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006847 spv::Id typeId1 = 0;
6848 if (consumedOperands > 1)
6849 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006850 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006851
6852 switch (op) {
6853 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006854 if (isFloat)
6855 libCall = spv::GLSLstd450FMin;
6856 else if (isUnsigned)
6857 libCall = spv::GLSLstd450UMin;
6858 else
6859 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006860 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006861 break;
6862 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006863 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006864 break;
6865 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006866 if (isFloat)
6867 libCall = spv::GLSLstd450FMax;
6868 else if (isUnsigned)
6869 libCall = spv::GLSLstd450UMax;
6870 else
6871 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006872 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006873 break;
6874 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006875 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006876 break;
6877 case glslang::EOpDot:
6878 opCode = spv::OpDot;
6879 break;
6880 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006881 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006882 break;
6883
6884 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006885 if (isFloat)
6886 libCall = spv::GLSLstd450FClamp;
6887 else if (isUnsigned)
6888 libCall = spv::GLSLstd450UClamp;
6889 else
6890 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006891 builder.promoteScalar(precision, operands.front(), operands[1]);
6892 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006893 break;
6894 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006895 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6896 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006897 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006898 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006899 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006900 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006901 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006902 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006903 break;
6904 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006905 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006906 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006907 break;
6908 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006909 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006910 builder.promoteScalar(precision, operands[0], operands[2]);
6911 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006912 break;
6913
6914 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006915 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006916 break;
6917 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006918 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006919 break;
6920 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006921 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006922 break;
6923 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006924 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006925 break;
6926 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006927 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006928 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006929 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006930#ifdef AMD_EXTENSIONS
6931 if (typeProxy == glslang::EbtFloat16)
6932 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6933#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006934 libCall = spv::GLSLstd450InterpolateAtSample;
6935 break;
6936 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006937#ifdef AMD_EXTENSIONS
6938 if (typeProxy == glslang::EbtFloat16)
6939 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6940#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006941 libCall = spv::GLSLstd450InterpolateAtOffset;
6942 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006943 case glslang::EOpAddCarry:
6944 opCode = spv::OpIAddCarry;
6945 typeId = builder.makeStructResultType(typeId0, typeId0);
6946 consumedOperands = 2;
6947 break;
6948 case glslang::EOpSubBorrow:
6949 opCode = spv::OpISubBorrow;
6950 typeId = builder.makeStructResultType(typeId0, typeId0);
6951 consumedOperands = 2;
6952 break;
6953 case glslang::EOpUMulExtended:
6954 opCode = spv::OpUMulExtended;
6955 typeId = builder.makeStructResultType(typeId0, typeId0);
6956 consumedOperands = 2;
6957 break;
6958 case glslang::EOpIMulExtended:
6959 opCode = spv::OpSMulExtended;
6960 typeId = builder.makeStructResultType(typeId0, typeId0);
6961 consumedOperands = 2;
6962 break;
6963 case glslang::EOpBitfieldExtract:
6964 if (isUnsigned)
6965 opCode = spv::OpBitFieldUExtract;
6966 else
6967 opCode = spv::OpBitFieldSExtract;
6968 break;
6969 case glslang::EOpBitfieldInsert:
6970 opCode = spv::OpBitFieldInsert;
6971 break;
6972
6973 case glslang::EOpFma:
6974 libCall = spv::GLSLstd450Fma;
6975 break;
6976 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006977 {
6978 libCall = spv::GLSLstd450FrexpStruct;
6979 assert(builder.isPointerType(typeId1));
6980 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006981 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006982#ifdef AMD_EXTENSIONS
6983 if (width == 16)
6984 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6985 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6986#endif
Rex Xu470026f2017-03-29 17:12:40 +08006987 if (builder.getNumComponents(operands[0]) == 1)
6988 frexpIntType = builder.makeIntegerType(width, true);
6989 else
6990 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6991 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6992 consumedOperands = 1;
6993 }
John Kessenich55e7d112015-11-15 21:33:39 -07006994 break;
6995 case glslang::EOpLdexp:
6996 libCall = spv::GLSLstd450Ldexp;
6997 break;
6998
Rex Xu574ab042016-04-14 16:53:07 +08006999 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007000 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007001
John Kessenich66011cb2018-03-06 16:12:04 -07007002 case glslang::EOpSubgroupBroadcast:
7003 case glslang::EOpSubgroupBallotBitExtract:
7004 case glslang::EOpSubgroupShuffle:
7005 case glslang::EOpSubgroupShuffleXor:
7006 case glslang::EOpSubgroupShuffleUp:
7007 case glslang::EOpSubgroupShuffleDown:
7008 case glslang::EOpSubgroupClusteredAdd:
7009 case glslang::EOpSubgroupClusteredMul:
7010 case glslang::EOpSubgroupClusteredMin:
7011 case glslang::EOpSubgroupClusteredMax:
7012 case glslang::EOpSubgroupClusteredAnd:
7013 case glslang::EOpSubgroupClusteredOr:
7014 case glslang::EOpSubgroupClusteredXor:
7015 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007016#ifdef NV_EXTENSIONS
7017 case glslang::EOpSubgroupPartitionedAdd:
7018 case glslang::EOpSubgroupPartitionedMul:
7019 case glslang::EOpSubgroupPartitionedMin:
7020 case glslang::EOpSubgroupPartitionedMax:
7021 case glslang::EOpSubgroupPartitionedAnd:
7022 case glslang::EOpSubgroupPartitionedOr:
7023 case glslang::EOpSubgroupPartitionedXor:
7024 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7025 case glslang::EOpSubgroupPartitionedInclusiveMul:
7026 case glslang::EOpSubgroupPartitionedInclusiveMin:
7027 case glslang::EOpSubgroupPartitionedInclusiveMax:
7028 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7029 case glslang::EOpSubgroupPartitionedInclusiveOr:
7030 case glslang::EOpSubgroupPartitionedInclusiveXor:
7031 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7032 case glslang::EOpSubgroupPartitionedExclusiveMul:
7033 case glslang::EOpSubgroupPartitionedExclusiveMin:
7034 case glslang::EOpSubgroupPartitionedExclusiveMax:
7035 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7036 case glslang::EOpSubgroupPartitionedExclusiveOr:
7037 case glslang::EOpSubgroupPartitionedExclusiveXor:
7038#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007039 return createSubgroupOperation(op, typeId, operands, typeProxy);
7040
Rex Xu9d93a232016-05-05 12:30:44 +08007041#ifdef AMD_EXTENSIONS
7042 case glslang::EOpSwizzleInvocations:
7043 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7044 libCall = spv::SwizzleInvocationsAMD;
7045 break;
7046 case glslang::EOpSwizzleInvocationsMasked:
7047 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7048 libCall = spv::SwizzleInvocationsMaskedAMD;
7049 break;
7050 case glslang::EOpWriteInvocation:
7051 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7052 libCall = spv::WriteInvocationAMD;
7053 break;
7054
7055 case glslang::EOpMin3:
7056 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7057 if (isFloat)
7058 libCall = spv::FMin3AMD;
7059 else {
7060 if (isUnsigned)
7061 libCall = spv::UMin3AMD;
7062 else
7063 libCall = spv::SMin3AMD;
7064 }
7065 break;
7066 case glslang::EOpMax3:
7067 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7068 if (isFloat)
7069 libCall = spv::FMax3AMD;
7070 else {
7071 if (isUnsigned)
7072 libCall = spv::UMax3AMD;
7073 else
7074 libCall = spv::SMax3AMD;
7075 }
7076 break;
7077 case glslang::EOpMid3:
7078 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7079 if (isFloat)
7080 libCall = spv::FMid3AMD;
7081 else {
7082 if (isUnsigned)
7083 libCall = spv::UMid3AMD;
7084 else
7085 libCall = spv::SMid3AMD;
7086 }
7087 break;
7088
7089 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007090 if (typeProxy == glslang::EbtFloat16)
7091 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007092 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7093 libCall = spv::InterpolateAtVertexAMD;
7094 break;
7095#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007096 case glslang::EOpBarrier:
7097 {
7098 // This is for the extended controlBarrier function, with four operands.
7099 // The unextended barrier() goes through createNoArgOperation.
7100 assert(operands.size() == 4);
7101 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7102 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7103 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7104 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7105 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7106 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7107 }
7108 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7109 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7110 }
7111 return 0;
7112 }
7113 break;
7114 case glslang::EOpMemoryBarrier:
7115 {
7116 // This is for the extended memoryBarrier function, with three operands.
7117 // The unextended memoryBarrier() goes through createNoArgOperation.
7118 assert(operands.size() == 3);
7119 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7120 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7121 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7122 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7123 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7124 }
7125 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7126 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7127 }
7128 return 0;
7129 }
7130 break;
Chao Chen3c366992018-09-19 11:41:59 -07007131
7132#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007133 case glslang::EOpReportIntersectionNV:
7134 {
7135 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007136 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007137 }
7138 break;
7139 case glslang::EOpTraceNV:
7140 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007141 builder.createNoResultOp(spv::OpTraceNV, operands);
7142 return 0;
7143 }
7144 break;
7145 case glslang::EOpExecuteCallableNV:
7146 {
7147 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007148 return 0;
7149 }
7150 break;
Chao Chen3c366992018-09-19 11:41:59 -07007151 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7152 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7153 return 0;
7154#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007155 case glslang::EOpCooperativeMatrixMulAdd:
7156 opCode = spv::OpCooperativeMatrixMulAddNV;
7157 break;
7158
John Kessenich140f3df2015-06-26 16:58:36 -06007159 default:
7160 return 0;
7161 }
7162
7163 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007164 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007165 // Use an extended instruction from the standard library.
7166 // Construct the call arguments, without modifying the original operands vector.
7167 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7168 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007169 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007170 } else if (opCode == spv::OpDot && !isFloat) {
7171 // int dot(int, int)
7172 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7173 const int componentCount = builder.getNumComponents(operands[0]);
7174 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7175 builder.setPrecision(mulOp, precision);
7176 id = builder.createCompositeExtract(mulOp, typeId, 0);
7177 for (int i = 1; i < componentCount; ++i) {
7178 builder.setPrecision(id, precision);
7179 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7180 }
John Kessenich2359bd02015-12-06 19:29:11 -07007181 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007182 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007183 case 0:
7184 // should all be handled by visitAggregate and createNoArgOperation
7185 assert(0);
7186 return 0;
7187 case 1:
7188 // should all be handled by createUnaryOperation
7189 assert(0);
7190 return 0;
7191 case 2:
7192 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7193 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007194 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007195 // anything 3 or over doesn't have l-value operands, so all should be consumed
7196 assert(consumedOperands == operands.size());
7197 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007198 break;
7199 }
7200 }
7201
John Kessenich55e7d112015-11-15 21:33:39 -07007202 // Decode the return types that were structures
7203 switch (op) {
7204 case glslang::EOpAddCarry:
7205 case glslang::EOpSubBorrow:
7206 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7207 id = builder.createCompositeExtract(id, typeId0, 0);
7208 break;
7209 case glslang::EOpUMulExtended:
7210 case glslang::EOpIMulExtended:
7211 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7212 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7213 break;
7214 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007215 {
7216 assert(operands.size() == 2);
7217 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7218 // "exp" is floating-point type (from HLSL intrinsic)
7219 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7220 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7221 builder.createStore(member1, operands[1]);
7222 } else
7223 // "exp" is integer type (from GLSL built-in function)
7224 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7225 id = builder.createCompositeExtract(id, typeId0, 0);
7226 }
John Kessenich55e7d112015-11-15 21:33:39 -07007227 break;
7228 default:
7229 break;
7230 }
7231
John Kessenich32cfd492016-02-02 12:37:46 -07007232 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007233}
7234
Rex Xu9d93a232016-05-05 12:30:44 +08007235// Intrinsics with no arguments (or no return value, and no precision).
7236spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007237{
Jeff Bolz36831c92018-09-05 10:11:41 -05007238 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7239 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007240
7241 switch (op) {
7242 case glslang::EOpEmitVertex:
7243 builder.createNoResultOp(spv::OpEmitVertex);
7244 return 0;
7245 case glslang::EOpEndPrimitive:
7246 builder.createNoResultOp(spv::OpEndPrimitive);
7247 return 0;
7248 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007249 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007250 if (glslangIntermediate->usingVulkanMemoryModel()) {
7251 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7252 spv::MemorySemanticsOutputMemoryKHRMask |
7253 spv::MemorySemanticsAcquireReleaseMask);
7254 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7255 } else {
7256 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7257 }
John Kessenich82979362017-12-11 04:02:24 -07007258 } else {
7259 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7260 spv::MemorySemanticsWorkgroupMemoryMask |
7261 spv::MemorySemanticsAcquireReleaseMask);
7262 }
John Kessenich140f3df2015-06-26 16:58:36 -06007263 return 0;
7264 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007265 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7266 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007267 return 0;
7268 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007269 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7270 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007271 return 0;
7272 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007273 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7274 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007275 return 0;
7276 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007277 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7278 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007279 return 0;
7280 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007281 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7282 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007283 return 0;
7284 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007285 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7286 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007287 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007288 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007289 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007290 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007291 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007292 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007293 case glslang::EOpDeviceMemoryBarrier:
7294 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7295 spv::MemorySemanticsImageMemoryMask |
7296 spv::MemorySemanticsAcquireReleaseMask);
7297 return 0;
7298 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7299 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7300 spv::MemorySemanticsImageMemoryMask |
7301 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007302 return 0;
7303 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007304 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7305 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007306 return 0;
7307 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007308 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7309 spv::MemorySemanticsWorkgroupMemoryMask |
7310 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007311 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007312 case glslang::EOpSubgroupBarrier:
7313 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7314 spv::MemorySemanticsAcquireReleaseMask);
7315 return spv::NoResult;
7316 case glslang::EOpSubgroupMemoryBarrier:
7317 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7318 spv::MemorySemanticsAcquireReleaseMask);
7319 return spv::NoResult;
7320 case glslang::EOpSubgroupMemoryBarrierBuffer:
7321 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7322 spv::MemorySemanticsAcquireReleaseMask);
7323 return spv::NoResult;
7324 case glslang::EOpSubgroupMemoryBarrierImage:
7325 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7326 spv::MemorySemanticsAcquireReleaseMask);
7327 return spv::NoResult;
7328 case glslang::EOpSubgroupMemoryBarrierShared:
7329 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7330 spv::MemorySemanticsAcquireReleaseMask);
7331 return spv::NoResult;
7332 case glslang::EOpSubgroupElect: {
7333 std::vector<spv::Id> operands;
7334 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7335 }
Rex Xu9d93a232016-05-05 12:30:44 +08007336#ifdef AMD_EXTENSIONS
7337 case glslang::EOpTime:
7338 {
7339 std::vector<spv::Id> args; // Dummy arguments
7340 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7341 return builder.setPrecision(id, precision);
7342 }
7343#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007344#ifdef NV_EXTENSIONS
7345 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007346 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007347 return 0;
7348 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007349 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007350 return 0;
7351#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007352 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007353 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007354 return 0;
7355 }
7356}
7357
7358spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7359{
John Kessenich2f273362015-07-18 22:34:27 -06007360 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007361 spv::Id id;
7362 if (symbolValues.end() != iter) {
7363 id = iter->second;
7364 return id;
7365 }
7366
7367 // it was not found, create it
7368 id = createSpvVariable(symbol);
7369 symbolValues[symbol->getId()] = id;
7370
Rex Xuc884b4a2016-06-29 15:03:44 +08007371 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007372 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7373 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7374 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007375#ifdef NV_EXTENSIONS
7376 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7377#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007378 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007379 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007380 if (symbol->getQualifier().hasIndex())
7381 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7382 if (symbol->getQualifier().hasComponent())
7383 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007384 // atomic counters use this:
7385 if (symbol->getQualifier().hasOffset())
7386 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007387 }
7388
scygan2c864272016-05-18 18:09:17 +02007389 if (symbol->getQualifier().hasLocation())
7390 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007391 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007392 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007393 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007394 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007395 }
John Kessenich140f3df2015-06-26 16:58:36 -06007396 if (symbol->getQualifier().hasSet())
7397 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007398 else if (IsDescriptorResource(symbol->getType())) {
7399 // default to 0
7400 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7401 }
John Kessenich140f3df2015-06-26 16:58:36 -06007402 if (symbol->getQualifier().hasBinding())
7403 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007404 else if (IsDescriptorResource(symbol->getType())) {
7405 // default to 0
7406 builder.addDecoration(id, spv::DecorationBinding, 0);
7407 }
John Kessenich6c292d32016-02-15 20:58:50 -07007408 if (symbol->getQualifier().hasAttachment())
7409 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007410 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007411 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007412 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007413 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007414 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7415 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7416 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7417 }
7418 if (symbol->getQualifier().hasXfbOffset())
7419 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007420 }
7421
Rex Xu1da878f2016-02-21 20:59:01 +08007422 if (symbol->getType().isImage()) {
7423 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007424 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007425 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007426 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007427 }
7428
John Kessenich140f3df2015-06-26 16:58:36 -06007429 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007430 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007431 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007432 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007433
John Kessenich5611c6d2018-04-05 11:25:02 -06007434 // nonuniform
7435 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7436
John Kessenichecba76f2017-01-06 00:34:48 -07007437#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007438 if (builtIn == spv::BuiltInSampleMask) {
7439 spv::Decoration decoration;
7440 // GL_NV_sample_mask_override_coverage extension
7441 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007442 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007443 else
7444 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007445 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007446 if (decoration != spv::DecorationMax) {
7447 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7448 }
7449 }
chaoc771d89f2017-01-13 01:10:53 -08007450 else if (builtIn == spv::BuiltInLayer) {
7451 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007452 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007453 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007454 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7455 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7456 }
John Kessenichb41bff62017-08-11 13:07:17 -06007457 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007458 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7459 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007460 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7461 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7462 }
7463 }
7464
chaoc6e5acae2016-12-20 13:28:52 -08007465 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007466 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007467 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007468 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7469 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007470 if (symbol->getQualifier().pervertexNV) {
7471 builder.addDecoration(id, spv::DecorationPerVertexNV);
7472 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7473 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7474 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007475#endif
7476
John Kessenich5d610ee2018-03-07 18:05:55 -07007477 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7478 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7479 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7480 symbol->getType().getQualifier().semanticName);
7481 }
7482
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007483 if (symbol->getBasicType() == glslang::EbtReference) {
7484 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7485 }
7486
John Kessenich140f3df2015-06-26 16:58:36 -06007487 return id;
7488}
7489
Chao Chen3c366992018-09-19 11:41:59 -07007490#ifdef NV_EXTENSIONS
7491// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7492void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7493{
7494 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007495 if (qualifier.perPrimitiveNV) {
7496 // Need to add capability/extension for fragment shader.
7497 // Mesh shader already adds this by default.
7498 if (glslangIntermediate->getStage() == EShLangFragment) {
7499 builder.addCapability(spv::CapabilityMeshShadingNV);
7500 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7501 }
Chao Chen3c366992018-09-19 11:41:59 -07007502 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007503 }
Chao Chen3c366992018-09-19 11:41:59 -07007504 if (qualifier.perViewNV)
7505 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7506 if (qualifier.perTaskNV)
7507 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7508 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007509 if (qualifier.perPrimitiveNV) {
7510 // Need to add capability/extension for fragment shader.
7511 // Mesh shader already adds this by default.
7512 if (glslangIntermediate->getStage() == EShLangFragment) {
7513 builder.addCapability(spv::CapabilityMeshShadingNV);
7514 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7515 }
Chao Chen3c366992018-09-19 11:41:59 -07007516 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007517 }
Chao Chen3c366992018-09-19 11:41:59 -07007518 if (qualifier.perViewNV)
7519 builder.addDecoration(id, spv::DecorationPerViewNV);
7520 if (qualifier.perTaskNV)
7521 builder.addDecoration(id, spv::DecorationPerTaskNV);
7522 }
7523}
7524#endif
7525
John Kessenich55e7d112015-11-15 21:33:39 -07007526// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007527// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007528//
7529// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7530//
7531// Recursively walk the nodes. The nodes form a tree whose leaves are
7532// regular constants, which themselves are trees that createSpvConstant()
7533// recursively walks. So, this function walks the "top" of the tree:
7534// - emit specialization constant-building instructions for specConstant
7535// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007536spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007537{
John Kessenich7cc0e282016-03-20 00:46:02 -06007538 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007539
qining4f4bb812016-04-03 23:55:17 -04007540 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007541 if (! node.getQualifier().specConstant) {
7542 // hand off to the non-spec-constant path
7543 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7544 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007545 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007546 nextConst, false);
7547 }
7548
7549 // We now know we have a specialization constant to build
7550
John Kessenichd94c0032016-05-30 19:29:40 -06007551 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007552 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7553 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7554 std::vector<spv::Id> dimConstId;
7555 for (int dim = 0; dim < 3; ++dim) {
7556 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7557 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007558 if (specConst) {
7559 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7560 glslangIntermediate->getLocalSizeSpecId(dim));
7561 }
qining4f4bb812016-04-03 23:55:17 -04007562 }
7563 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7564 }
7565
7566 // An AST node labelled as specialization constant should be a symbol node.
7567 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7568 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007569 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007570 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007571 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7572 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7573 // will set the builder into spec constant op instruction generating mode.
7574 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007575 result = accessChainLoad(sub_tree->getType());
7576 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007577 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007578 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007579 } else {
7580 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007581 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007582 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007583 builder.addName(result, sn->getName().c_str());
7584 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007585 }
qining4f4bb812016-04-03 23:55:17 -04007586
7587 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7588 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007589 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007590 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007591}
7592
John Kessenich140f3df2015-06-26 16:58:36 -06007593// Use 'consts' as the flattened glslang source of scalar constants to recursively
7594// build the aggregate SPIR-V constant.
7595//
7596// If there are not enough elements present in 'consts', 0 will be substituted;
7597// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7598//
qining08408382016-03-21 09:51:37 -04007599spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007600{
7601 // vector of constants for SPIR-V
7602 std::vector<spv::Id> spvConsts;
7603
7604 // Type is used for struct and array constants
7605 spv::Id typeId = convertGlslangToSpvType(glslangType);
7606
7607 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007608 glslang::TType elementType(glslangType, 0);
7609 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007610 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007611 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007612 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007613 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007614 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007615 } else if (glslangType.isCoopMat()) {
7616 glslang::TType componentType(glslangType.getBasicType());
7617 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007618 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007619 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7620 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007621 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007622 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007623 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7624 bool zero = nextConst >= consts.size();
7625 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007626 case glslang::EbtInt8:
7627 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7628 break;
7629 case glslang::EbtUint8:
7630 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7631 break;
7632 case glslang::EbtInt16:
7633 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7634 break;
7635 case glslang::EbtUint16:
7636 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7637 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007638 case glslang::EbtInt:
7639 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7640 break;
7641 case glslang::EbtUint:
7642 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7643 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007644 case glslang::EbtInt64:
7645 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7646 break;
7647 case glslang::EbtUint64:
7648 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7649 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007650 case glslang::EbtFloat:
7651 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7652 break;
7653 case glslang::EbtDouble:
7654 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7655 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007656 case glslang::EbtFloat16:
7657 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7658 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007659 case glslang::EbtBool:
7660 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7661 break;
7662 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007663 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007664 break;
7665 }
7666 ++nextConst;
7667 }
7668 } else {
7669 // we have a non-aggregate (scalar) constant
7670 bool zero = nextConst >= consts.size();
7671 spv::Id scalar = 0;
7672 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007673 case glslang::EbtInt8:
7674 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7675 break;
7676 case glslang::EbtUint8:
7677 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7678 break;
7679 case glslang::EbtInt16:
7680 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7681 break;
7682 case glslang::EbtUint16:
7683 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7684 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007685 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007686 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007687 break;
7688 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007689 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007690 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007691 case glslang::EbtInt64:
7692 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7693 break;
7694 case glslang::EbtUint64:
7695 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7696 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007697 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007698 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007699 break;
7700 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007701 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007702 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007703 case glslang::EbtFloat16:
7704 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7705 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007706 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007707 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007708 break;
7709 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007710 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007711 break;
7712 }
7713 ++nextConst;
7714 return scalar;
7715 }
7716
7717 return builder.makeCompositeConstant(typeId, spvConsts);
7718}
7719
John Kessenich7c1aa102015-10-15 13:29:11 -06007720// Return true if the node is a constant or symbol whose reading has no
7721// non-trivial observable cost or effect.
7722bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7723{
7724 // don't know what this is
7725 if (node == nullptr)
7726 return false;
7727
7728 // a constant is safe
7729 if (node->getAsConstantUnion() != nullptr)
7730 return true;
7731
7732 // not a symbol means non-trivial
7733 if (node->getAsSymbolNode() == nullptr)
7734 return false;
7735
7736 // a symbol, depends on what's being read
7737 switch (node->getType().getQualifier().storage) {
7738 case glslang::EvqTemporary:
7739 case glslang::EvqGlobal:
7740 case glslang::EvqIn:
7741 case glslang::EvqInOut:
7742 case glslang::EvqConst:
7743 case glslang::EvqConstReadOnly:
7744 case glslang::EvqUniform:
7745 return true;
7746 default:
7747 return false;
7748 }
qining25262b32016-05-06 17:25:16 -04007749}
John Kessenich7c1aa102015-10-15 13:29:11 -06007750
7751// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007752// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007753// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007754// Return true if trivial.
7755bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7756{
7757 if (node == nullptr)
7758 return false;
7759
John Kessenich84cc15f2017-05-24 16:44:47 -06007760 // count non scalars as trivial, as well as anything coming from HLSL
7761 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007762 return true;
7763
John Kessenich7c1aa102015-10-15 13:29:11 -06007764 // symbols and constants are trivial
7765 if (isTrivialLeaf(node))
7766 return true;
7767
7768 // otherwise, it needs to be a simple operation or one or two leaf nodes
7769
7770 // not a simple operation
7771 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7772 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7773 if (binaryNode == nullptr && unaryNode == nullptr)
7774 return false;
7775
7776 // not on leaf nodes
7777 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7778 return false;
7779
7780 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7781 return false;
7782 }
7783
7784 switch (node->getAsOperator()->getOp()) {
7785 case glslang::EOpLogicalNot:
7786 case glslang::EOpConvIntToBool:
7787 case glslang::EOpConvUintToBool:
7788 case glslang::EOpConvFloatToBool:
7789 case glslang::EOpConvDoubleToBool:
7790 case glslang::EOpEqual:
7791 case glslang::EOpNotEqual:
7792 case glslang::EOpLessThan:
7793 case glslang::EOpGreaterThan:
7794 case glslang::EOpLessThanEqual:
7795 case glslang::EOpGreaterThanEqual:
7796 case glslang::EOpIndexDirect:
7797 case glslang::EOpIndexDirectStruct:
7798 case glslang::EOpLogicalXor:
7799 case glslang::EOpAny:
7800 case glslang::EOpAll:
7801 return true;
7802 default:
7803 return false;
7804 }
7805}
7806
7807// Emit short-circuiting code, where 'right' is never evaluated unless
7808// the left side is true (for &&) or false (for ||).
7809spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7810{
7811 spv::Id boolTypeId = builder.makeBoolType();
7812
7813 // emit left operand
7814 builder.clearAccessChain();
7815 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007816 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007817
7818 // Operands to accumulate OpPhi operands
7819 std::vector<spv::Id> phiOperands;
7820 // accumulate left operand's phi information
7821 phiOperands.push_back(leftId);
7822 phiOperands.push_back(builder.getBuildPoint()->getId());
7823
7824 // Make the two kinds of operation symmetric with a "!"
7825 // || => emit "if (! left) result = right"
7826 // && => emit "if ( left) result = right"
7827 //
7828 // TODO: this runtime "not" for || could be avoided by adding functionality
7829 // to 'builder' to have an "else" without an "then"
7830 if (op == glslang::EOpLogicalOr)
7831 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7832
7833 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007834 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007835
7836 // emit right operand as the "then" part of the "if"
7837 builder.clearAccessChain();
7838 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007839 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007840
7841 // accumulate left operand's phi information
7842 phiOperands.push_back(rightId);
7843 phiOperands.push_back(builder.getBuildPoint()->getId());
7844
7845 // finish the "if"
7846 ifBuilder.makeEndIf();
7847
7848 // phi together the two results
7849 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7850}
7851
Frank Henigman541f7bb2018-01-16 00:18:26 -05007852#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007853// Return type Id of the imported set of extended instructions corresponds to the name.
7854// Import this set if it has not been imported yet.
7855spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7856{
7857 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7858 return extBuiltinMap[name];
7859 else {
Rex Xu51596642016-09-21 18:56:12 +08007860 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007861 spv::Id extBuiltins = builder.import(name);
7862 extBuiltinMap[name] = extBuiltins;
7863 return extBuiltins;
7864 }
7865}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007866#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007867
John Kessenich140f3df2015-06-26 16:58:36 -06007868}; // end anonymous namespace
7869
7870namespace glslang {
7871
John Kessenich68d78fd2015-07-12 19:28:10 -06007872void GetSpirvVersion(std::string& version)
7873{
John Kessenich9e55f632015-07-15 10:03:39 -06007874 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007875 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007876 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007877 version = buf;
7878}
7879
John Kessenicha372a3e2017-11-02 22:32:14 -06007880// For low-order part of the generator's magic number. Bump up
7881// when there is a change in the style (e.g., if SSA form changes,
7882// or a different instruction sequence to do something gets used).
7883int GetSpirvGeneratorVersion()
7884{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007885 // return 1; // start
7886 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007887 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007888 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007889 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007890 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7891 // versions 4 and 6 each generate OpArrayLength as it has long been done
7892 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007893}
7894
John Kessenich140f3df2015-06-26 16:58:36 -06007895// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007896void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007897{
7898 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007899 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007900 if (out.fail())
7901 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007902 for (int i = 0; i < (int)spirv.size(); ++i) {
7903 unsigned int word = spirv[i];
7904 out.write((const char*)&word, 4);
7905 }
7906 out.close();
7907}
7908
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007909// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007910void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007911{
7912 std::ofstream out;
7913 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007914 if (out.fail())
7915 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007916 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007917 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007918 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007919 if (varName != nullptr) {
7920 out << "\t #pragma once" << std::endl;
7921 out << "const uint32_t " << varName << "[] = {" << std::endl;
7922 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007923 const int WORDS_PER_LINE = 8;
7924 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7925 out << "\t";
7926 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7927 const unsigned int word = spirv[i + j];
7928 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7929 if (i + j + 1 < (int)spirv.size()) {
7930 out << ",";
7931 }
7932 }
7933 out << std::endl;
7934 }
Flavio15017db2017-02-15 14:29:33 -08007935 if (varName != nullptr) {
7936 out << "};";
7937 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007938 out.close();
7939}
7940
John Kessenich140f3df2015-06-26 16:58:36 -06007941//
7942// Set up the glslang traversal
7943//
John Kessenich4e11b612018-08-30 16:56:59 -06007944void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007945{
Lei Zhang17535f72016-05-04 15:55:59 -04007946 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007947 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007948}
7949
John Kessenich4e11b612018-08-30 16:56:59 -06007950void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007951 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007952{
John Kessenich140f3df2015-06-26 16:58:36 -06007953 TIntermNode* root = intermediate.getTreeRoot();
7954
7955 if (root == 0)
7956 return;
7957
John Kessenich4e11b612018-08-30 16:56:59 -06007958 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007959 if (options == nullptr)
7960 options = &defaultOptions;
7961
John Kessenich4e11b612018-08-30 16:56:59 -06007962 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007963
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007964 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007965 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007966 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007967 it.dumpSpv(spirv);
7968
GregFfb03a552018-03-29 11:49:14 -06007969#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007970 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7971 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007972 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007973 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007974
John Kessenich4e11b612018-08-30 16:56:59 -06007975 if (options->validate)
7976 SpirvToolsValidate(intermediate, spirv, logger);
7977
John Kessenich717c80a2018-08-23 15:17:10 -06007978 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007979 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007980
GregFcd1f1692017-09-21 18:40:22 -06007981#endif
7982
John Kessenich4e11b612018-08-30 16:56:59 -06007983 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007984}
7985
7986}; // end namespace glslang